Reputation: 1825
What are the differences between preg_replace()
and preg_filter()
?
In which situations should I use one instead of the other?
I tried reading the documentation, but still don't quite understand what the differences are.
Upvotes: 7
Views: 4399
Reputation: 47894
Both functions can process string-type (well, scalar-type values) input or a flat array and are primarily designed to return string or array type data -- depending on the input data-type. If preg_filter()
receives a string but it does not satisfy the regex logic, then null
will be returned. With either function, if there is an error, null
will be returned.
preg_replace()
will mutate the data, but has no ability to remove elements; the only reason to ever use preg_filter()
is when you wish to mutate the input value(s) AND remove the unaffected value(s).
preg_filter()
behaves like preg_replace()
followed by a destructive step where unaffected values are either removed from the array or the string is converted to null
. Like preg_replace()
, preg_filter()
has the ability to optionally limit replacements per string and count the number of replacements performed in the entire process.
Array test: (Demo)
$array = [
"💩 happens",
"I'm getting too old for this 💩",
"shiitake",
"Mondays are 💩, Tuesdays are 💩, and so on!",
"Here is your Finnish itinerary",
"Is this chocolate or 💩?"
];
var_export(
preg_filter('/💩/u', 'poop', $array, 1, $count) // parameters 4 and 5 are optional
);
echo "\n---\ncount: $count";
Output:
array (
0 => 'poop happens',
1 => 'I\'m getting too old for this poop',
3 => 'Mondays are poop, Tuesdays are 💩, and so on!',
5 => 'Is this chocolate or poop?',
)
---
count: 4
String Tests: (Demo)
var_export(
preg_filter('/💩/u', 'poop', "Mondays are 💩, Tuesdays are 💩, and so on!", 1, $count)
);
echo "\n---\ncount: $count\n===\n";
var_export(
preg_filter('/💩/u', 'poop', "shiitake", 1, $count)
);
echo "\n---\ncount: $count";
Output:
'Mondays are poop, Tuesdays are 💩, and so on!'
---
count: 1
===
NULL
---
count: 0
Upvotes: 0
Reputation: 5432
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'
Upvotes: 2
Reputation: 29912
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
Upvotes: 1