编辑这个页面须要登录或更高权限!
preg_filter 函数用于执行一个正则表达式搜索和替换。
mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
preg_filter() 等价于 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 返回值:\n";
print_r(preg_filter($pattern, $replace, $subject));
echo "preg_replace 返回值:\n";
print_r(preg_replace($pattern, $replace, $subject));
?>
执行结果如下所示:
preg_filter 返回值: Array ( [0] => A:C:1 [1] => B:C:a [2] => A:2 [3] => B:b [4] => A:3 [7] => A:4 ) preg_replace 返回值: 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 )
可以看出 preg_filter 只返回匹配结果,不匹配的直接忽略,而 preg_replace 将不匹配的结果 'A' 'B' 元素也一起返回。