Recursive str_replace in PHP

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

Tags: , , ,

2 Responses to “Recursive str_replace in PHP”

  1. Casey TompkinsNo Gravatar says:

    Any reason not to just do a while loop using strpos?

  2. JamesNo Gravatar says:

    Good point, thanks.

Leave a Reply