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?

5
  • Why don't you use str_replace() then? Commented Apr 13, 2015 at 6:31
  • 7
    Presort the replacement patterns by their length and apply them downwards? Commented Apr 13, 2015 at 6:31
  • Or use word boundaries in your regular expression Commented Apr 13, 2015 at 6:36
  • @arkascha Why not making an answer out of it? Then the question wouldn't stay open. Commented Apr 13, 2015 at 8:12
  • @hek2mgl As you like. Thanks. Commented Apr 13, 2015 at 8:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

An example would be nice ;)
@hek2mgl an example of sorting something by length? Come on... no code in the question => no code in the answer.
Thanks, it is exactly what I missed in my logic, thanks, mate :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.