This doesnt seem like it is any different from my code except that it is on one line.
The problem is that if $searchstring contains "foo" and $texttosearch contains "Foo" (note the case difference) when the replace occurs $texttosearch now contains "foo" instead of "Foo".
The code provided by sean does however solve the problem. Thanks for your suggestion though.