详细介绍PHP中preg_filter()与preg_replace()的区别

来自:互联网
时间:2021-07-06
阅读:

怎么说呢 正则替换过滤函数 跟先前我们说的替换函数很类似 ,就只有一点点的小区分 不知道大家发现没有!!

==preg_filter()==函数: 执行一个正则表达式搜索和替换

通常情况下preg_filter()函数等价于preg_replace()函数

案例1代码如下:

$arr=array('1.jpg','2.txt','3.doc','4.exe','5.php');
$pattern='/\.jpg|\.txt/';$replacement='';
$result1=preg_replace($pattern, $replacement, $arr);
$result2=preg_filter($pattern, $replacement, $arr);
show($result2);

preg_filter()和preg_replace()的实际区别

案例2代码如下:

$pattern=array(
    "/\d+/",
    "/ccc/");
$replacement=array(
    '1024',
    'PHP');
$string=array(
    '1234aaa',
    'abbbccc',
    'wampserver');
  $result1=preg_replace($pattern, $replacement, $string);
  show($result1);
  $result2=preg_filter($pattern, $replacement, $string);
  show($result2);

所以区别如下:

preg_filter()只会返回发生替换过滤后的数组元素,而没有替换的数组元素没有返回

preg_replace() 返回的不仅是发生替换过滤后的数组元素,并且没有发生替换的元素也会保留下来并且返回!

其实大家只要一测试打印 出彼此的结果 就可以马上知道相互之间的区别了 !

返回顶部
顶部