str_replace
replaces all occurrences of a word with a replacement.
preg_replace
replaces occurrences of a pattern with a replacement and takes an optional limit param.
I don't have any need for pattern matching but would like the convenience of a limit param. What should I be using?
This is an enhanced version of @brad-christie's answer which ads compatibility for arrays as $find and $replace values:
function str_replace_limit($find, $replacement, $subject, $limit = 0) {
if ($limit == 0)
return str_replace($find, $replacement, $subject);
for ($i = 0; $i < count($find); $i++) {
$find[$i] = '/' . preg_quote($find[$i],'/') . '/';
}
return preg_replace($find, $replacement, $subject, $limit);
}
function str_replace2($find, $replacement, $subject, $limit = 0){
if ($limit == 0)
return str_replace($find, $replacement, $subject);
$ptn = '/' . preg_quote($find,'/') . '/';
return preg_replace($ptn, $replacement, $subject, $limit);
}
That will allow you to place a limit on the number of replaces. Strings should be escaped using preg_quote
to make sure any special characters aren't interpreted as a pattern character.
Demo, BTW
In case you're interested, here's a version that includes the &$count
argument:
function str_replace2($find, $replacement, $subject, $limit = 0, &$count = 0){
if ($limit == 0)
return str_replace($find, $replacement, $subject, $count);
$ptn = '/' . preg_quote($find,'/') . '/';
return preg_replace($ptn, $replacement, $subject, $limit, $count);
}
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