Recursive str_replace and str_ireplace PHP

October 28, 2010
Use the functions below to recursively replace text the same way you would with str_replace and str_ireplace in PHP, however these functions perform a recursive (repeating) match and replace process.

<?PHP
function recursive_str_ireplace($replacethis,$withthis,$inthis)
     {
     while (1==1)
          {
          $inthis = str_ireplace($replacethis,$withthis,$inthis);
          if(stristr($inthis, $replacethis) === FALSE)
               {
               RETURN $inthis;
               }
          }
     RETURN $inthis;
     }
     
function recursive_str_replace($replacethis,$withthis,$inthis)
     {
     while (1==1)
          {
          $inthis = str_replace($replacethis,$withthis,$inthis);
          if(strstr($inthis, $replacethis) === FALSE)
               {
               RETURN $inthis;
               }
          }
     RETURN $inthis;
     }
     
     
echo recursive_str_replace("||","|","|||Hello||||||||");
echo "<br />";

echo str_replace("||","|","|||Hello||||||||");

This will yield the following

|Hello|
||Hello||||

As you can see by the replacement, the first one performed a recursive replacement, however the standard PHP one did not. There are still three replaceable "||" values in the string. This isn't a defect in PHP, it was intentional, however this recursive replace does a little something extra.

As-processed Example


1. |||Hello||||||||
2. ||Hello|||| ← str_replace's output
3. |Hello||
4. |Hello| ← recursive_str_replace's output



Feel free to reuse this code in any application, opensource, freeware, or commercial. If you do decide to use it, please drop a comment below:
Name:

No comments yet! Be the first!