Recursive str_replace and str_ireplace PHP
October 28, 2010| Tweet |
<?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: No comments yet! Be the first!

Facebook
LinkedIn