I am not really answering your question directly, and this may not be practical in your case, but did you know you can use a mysql function REPLACE() to replace strings without having to resort to involving PHP at all.
If you do not use mysql, then I imagine your chosen RDBMS may well have a similar function.