Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace vs preg_filter

Tags:

php

What are the differences between preg_replace and preg_filter? Are there any advantages when using one of them instead of the other in certain situations? I tried reading the docs but still don't quite understand what the differences are. Please enlighten me. Thanks.

like image 964
siaooo Avatar asked Jun 13 '12 06:06

siaooo


2 Answers

The advantage of preg_filter over preg_replace is that you can check whether or not anything was replaced, because preg_filter returns null if nothing was replaced, while preg_replace returns the subject regardless.

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

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

echo preg_replace($pattern, $replacement, $subject); // 'chips'
like image 51
Geoffrey Avatar answered Sep 28 '22 03:09

Geoffrey


preg_filter() is identical to preg_replace() except it only returns the (possibly transformed) subjects where there was a match. For details about how this function works, read the preg_replace() documentation.

from: here

So if the signature is

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

it returns the $subject arguments "transformed" (all the match with regex pattern are substitute) into an array

like image 37
DonCallisto Avatar answered Sep 28 '22 02:09

DonCallisto