When using this method, $lstr is used to find matches with the search string, and the numerical positioning results are used to change $str. The problem is that is $search and $replace are not the correct size, then the length of $str will change but the length of $lstr will not. There is no problem when the first match is done, but the second and subsequent matches will fail.
To fix this, the following line should be added at the top of the function:
$lendif = strlen($replace) - strlen($search);
and the line
$matched += $mlen;
should be changed to:
$matched += $mlen + $lendif;