I am trying to remove the word "John" a certain number of times from a string. I read in the php manual that str_replace excludes the 4th parameter called "count". So I decided what could be used to indicate how many search instances to remove. But this is not like the following:
$string = 'Hello John, how are you John. John are you happy with your life John?';
$numberOfInstances = 2;
echo str_replace('John', 'dude', $string, $numberOfInstances);
replaces all instances of the word "John" with "dude" instead of doing it only twice and leaving the other two Jones alone.
For my purposes, it does not matter in which order the replacement occurs, for example, the first 2 copies can be replaced, or the last two or a combination, the replacement order does not matter.
So, is there a way to use str_replace () this way or is there another built-in function (non-regex) that can achieve what I'm looking for?
source
share