0

I need to replace a huge amount of words and phrases in long strings, words and phrases might repeat several times.

I have successfully built a preg_replace() arrays and it works nearly well. The only problem is that the list of words and phrases to replace I want to have is overlapping, for example:

"acid" ---> "replacement1"

"light acid" --> "replacement2"

and it makes preg_replace to complain, as "acid" is in both, which is not surprising.

The question: How to build a proper function to replace words and phrases like in my scenario?

Gunaseelan
  • 2,494
  • 5
  • 36
  • 43
jerome
  • 19
  • 3

1 Answers1

1

Just presort the replacement patterns by their length and apply them downwards. That way longer strings will get replaced first. Therefore any contained substring in there cannot be replaced accidentally by other, shorter replacement rules.

arkascha
  • 41,620
  • 7
  • 58
  • 90