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).



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.
Your site is very useful for me to do many steps.
Your str_replace_every_other() function just saved me hours of time! I used it to take over 1000 lines of sorted table data and build it into a multidimensional array.
I’m on an apache server, and it rejected your str_replace_every_other() function the first time I ran it, because of the equal signs in the optional parameters. I simply changed the “&$count=null, $replace_first=true” to “$count, $replace_first” and made sure to supply the parameters. After the change, I received the result I was looking for. So, if you’re encountering the same problem, that’s the solution that worked for me.
Thanks Aaron!