preg_replace vs preg_filter

时间:2012-06-13 06:54:07

标签: php

preg_replacepreg_filter之间有什么区别?在某些情况下使用其中一个而不是另一个有什么优势吗?我试过阅读文档,但仍然不太明白差异是什么。请赐教。感谢。

2 个答案:

答案 0 :(得分:1)

  

preg_filter()与preg_replace()相同,只是它只返回匹配的(可能已转换的)主题。有关此函数如何工作的详细信息,请阅读preg_replace()文档。

来自:here

所以如果签名是

preg_filter ( mixed $pattern , mixed $replacement , 
              mixed $subject [, int $limit = -1 [, int &$count ]] )

它返回$subject个参数“transformed”(所有匹配regex pattern都是替换的)到数组中

答案 1 :(得分:1)

preg_filter优于preg_replace的优势在于您可以检查是否有任何内容被替换,因为preg_filter如果没有替换任何内容则返回null,而preg_replace则返回无论如何。

$subject = 'chips';
$pattern = '/chops/';
$replacement = 'flops';

if (is_null(preg_filter($pattern, $replacement, $subject)) { // true
    // do something
}

echo preg_replace($pattern, $replacement, $subject); // 'chips'
相关问题