0

How can I use PHP's preg_replace to replace all occurrence of a string within a text except for those found inside of a html's A tag ie: rest

for example, I want to replace the word color with the word blue.

**Original text**:
    Tim's favorite color is color.
    Color is also Bill's favorite.
**Converted text**:
    Tim's favorite color is blue.
    Blue is also Bill's favorite.
Mr. O
  • 11
  • 3
  • 4
    Simple: you don't. regexes and html don't play together nicely. Use a DOM parser. – Marc B Apr 20 '16 at 18:10
  • 1
    Zalgo is Tony the pony, he comes. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – ceejayoz Apr 20 '16 at 18:19

1 Answers1

0

I guess the best approach here would be to replace ALL instances of that word with the specified word. Then you should replace the text inside of the A Tag with the original word

So using your example:

**Original text**:
    Tim's favorite [color] is color.
    Color is also Bill's favorite.

**Interim step text**:
    Tim's favorite [blue] is blue.
    Blue is also Bill's favorite.

**Converted text**:
    Tim's favorite [color] is blue.
    Blue is also Bill's favorite.

The problems you will run into with this method are:

  1. Being context aware so you capitalize the replaced word in the second sentance. (Your description of the problem didn't cover that but the example did)
  2. Recognizing all links regardless of structure via regular expression

As such I haven't include any code, but I hope this puts you on the right track.

Nullsig
  • 38
  • 4