preg_filter 函數(shù)用于執(zhí)行一個(gè)正則表達(dá)式搜索和替換。
mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
preg_filter() 等價(jià)于 preg_replace() ,但它僅僅返回與目標(biāo)匹配的結(jié)果。
參數(shù)說(shuō)明:
<?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));
?>
執(zhí)行結(jié)果如下所示:
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 只返回匹配結(jié)果,不匹配的直接忽略,而 preg_replace 將不匹配的結(jié)果 'A' 'B' 元素也一起返回。