PHP preg_filter() Function
PHP Regular Expressions (PCRE)
preg_filter The function performs a regular expression search and replace.
Syntax
mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
preg_filter() is equivalent to preg_replace(), but it only returns the results that match the target.
Parameter Description:
- $pattern: the pattern to search for. Can be a string or an array of strings.
- $replacement: the string or array of strings used for replacement.
- $subject: the string or array of strings to be searched and replaced.
- $limit: optional, the maximum number of replacements each pattern performs on each subject. Default is -1 (unlimited).
- $count: optional, the number of replacements performed.
Example
Example comparing preg_filter() and preg_replace()
The execution result is as follows:
preg_filter return value:
Array
(
[0] => A:C:1
[1] => B:C:a
[2] => A:2
[3] => B:b
[4] => A:3
[7] => A:4
)
preg_replace return value:
Array
(
[0] => A:C:1
[1] => B:C:a
[2] => A:2
[3] => B:b
[4] => A:3
[5] => A
[6] => B
[7] => A:4
)
It can be seen that preg_filter only returns the matching results and ignores the non-matching ones, while preg_replace also returns the non-matching results 'A' and 'B' elements.