Easy Tutorial
❮ Func Filesystem Ftell Func Math Hexdec ❯

PHP preg_filter() Function

PHP Regular Expressions (PCRE)

The preg_filter function is used to perform 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 descriptions:

Example

Example Comparing preg_filter() and preg_replace()

<?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4'); 
$pattern = array('/\d/', '/[a-z]/', '/[1a]/'); 
$replace = array('A:$0', 'B:$0', 'C:$0'); 

echo "preg_filter return value:\n";
print_r(preg_filter($pattern, $replace, $subject)); 

echo "preg_replace return value:\n";
print_r(preg_replace($pattern, $replace, $subject)); 
?>

Execution results are 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 non-matching elements, while preg_replace also returns non-matching elements such as 'A' and 'B'.

PHP Regular Expressions (PCRE)

❮ Func Filesystem Ftell Func Math Hexdec ❯