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).'rn';
//two two one two two two
echo str_replace_every_other('one', 'two', $str, $count, false).'rn';
//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).

About Aaron D. Campbell

Owner and lead developer at BlueDog, Aaron has 10+ years of web development experience, it a regular core contributor to the WordPress project, and has released many WordPress plugins.
This entry was posted in PHP and tagged . Bookmark the permalink.

3 thoughts on “Replace every other occurrence with str_replace

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

  2. Y920.com says:

    Your site is very useful for me to do many steps.

  3. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *

Note: If you are replying to another commenter, click the "Reply to {NAME} ↵" button under their comment!