0

Wondering if there is a handy preg_replace or similar function that will change all my & to & but will not change & to & (won't change an & that is already in the proper format).

I am having problem displaying a page that has (user submitted) & and I wanted to change them (from a block of text fetched from mysql) just before displaying in the page.

Help will be appreciated. Cheers.

PS: I thought of using a str_replace with an & with space on either side, but then I stopped thinking about typos like Bob &Jenny in lieu of Bob & Jenny (since user submitted).

Jeremy Roy
  • 1,291
  • 5
  • 18
  • 31

1 Answers1

1

You can use an ?! assertion for that:

$html = preg_replace('/&(?!#?\w+;)/', "&", $html);
              # or just (?!amp;)

This also skips existing & and other < or { entities. But it's certainly not faultless.

mario
  • 144,265
  • 20
  • 237
  • 291