Optimize the string replacement function.