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.
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With