Posts Tagged ‘recursion’

Recursive str_replace in PHP

Thursday, March 20th, 2008
No Gravatar

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.


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?)

  • Share/Bookmark