Recursive str_replace in PHP
I was looking for a recursive str_replace in php tonight and I couldn’t find any, so I wrote one. This takes the exact same parameters as str_replace, in the same order. It recursively searches the $subject, replacing $search with $replace, while keeping track of how many times ($count) it has replaced the $subject.
<? function str_replace_recursive($search,$replace,$subject,&$count=0){ $newcount=$count; $subject = str_replace($search,$replace,$subject,$newcount); $count = $newcount+$count; if(!(strpos($subject,$search)===false)){ return str_replace_recursive($search,$replace,$subject,$count); }else{ return $subject; } } ?>
Example:
$count=0;
$string = "; ; I; am; ; ; ; ; become; ; ; ; ; ; ; ; ;";
string = str_replace_recursive('; ;',';',$string,$count);
echo $string;
echo $count;
Outputs:
string --> I; am; become;
count --> 12
(Note that this is not the best code to use for this situation; can you write a faster solution to this example using only plain vanilla str_replace?)
Tags: functions, php, recursion, str_replace