str_replace
replaces all occurrences of a word with a replacement.
preg_replace
replaces occurrences of a pattern with a replacement and ta
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);
}