English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and Example of PHP preg_filter() Function

PHP Regular Expression (PCRE)

preg_filter The 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 Description:

  • $pattern: The pattern to be searched. It can be a string or a string array.
  • $replacement: The string or string array to be used for replacement.
  • $subject: The string or string array to be searched and replaced.
  • $limit: Optional, the maximum number of replacements for each pattern on each subject. The default is -1(Unlimited).
  • $count: Optional, the number of replacements completed.

Online Example

<?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)); 
?>

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 matched results, and the unmatched ones are ignored directly, while preg_replace also returns the 'A' and 'B' elements that do not match.

PHP Regular Expression (PCRE)