July 5th, 2007 Replace every other occurrence with str_replace
Well, someone put some code onto the str_replace PHP manual page to replace every other occurrence of a string with another string. However, it didn’t work, and was simply spam to get a link onto the PHP manual page (shame on them). So I made a function that DID work, for the poor lost souls who would be trying over and over to make that one work. I figured that since I made it, I might as well post it, maybe someone needs something like this.
/** * Replaces every other occurrence of search in haystack with replace * * @param $needle mixed * @param $replace mixed * @param $haystack mixed * @param $count int[optional] * @param $replace_first bool[optional] - Default true * @return mixed */ function str_replace_every_other($needle, $replace, $haystack, &$count=null, $replace_first=true) { $count = 0; $offset = strpos($haystack, $needle); //If we don't replace the first, go ahead and skip it if (!$replace_first) { $offset += strlen($needle); $offset = strpos($haystack, $needle, $offset); } while ($offset !== false) { $haystack = substr_replace($haystack, $replace, $offset, strlen($needle)); $count++; $offset += strlen($replace); $offset = strpos($haystack, $needle, $offset); if ($offset !== false) { $offset += strlen($needle); $offset = strpos($haystack, $needle, $offset); } } return $haystack; }
//Use it like this:
$str = “one two one two one two”;
echo str_replace_every_other(’one’, ‘two’, $str, $count).’\r\n’;
//two two one two two two
echo str_replace_every_other(’one’, ‘two’, $str, $count, false).’\r\n’;
//one two two two one two
I added the last option ($replace_first) to let you replace the odd occurrences (true, default) or the evens (false).
Aaron D. Campbell Says:
Well, it’s not real easy with that function, but basically, when you see $offset = strpos(…), that’s skipping some space in the string. You should be able to duplicate those commands.