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:

Posted: Friday, December 17, 2010 at 12:51:04 PM
By: Jon
Thanks for the code!

The functions can be more compact and efficient, though:


function recursivestrreplace($replacethis,$withthis,$inthis)
while (strstr($inthis, $replacethis))
$inthisstrreplace($replacethis,$withthis,$inthis)

return $inthis



Does the same thing as the function you have
(I'm using my own code formatting. Format how you like. :D)
Posted: Friday, December 17, 2010 at 12:54:07 PM
By: Jon
Gah! The comment form stripped curly braces...

see: http:pastebin.compXLEsCMD