简体   繁体   中英

php - preg_replace a character not followed by a specific character

I have a string:

this &foo and&foo but not &#bar haius&#bar

All "&foo" should be replaced by "&foo" and "&#bar" should be left untouched. Ie any & not followed by a # should be replaced. Any ideas?

I've tried the following but it's not going very well...

preg_replace('/&*$[#]*$/', '&', "this &foo and&foo but not &#bar haius&#bar");

Thanks for any help!

You can use a negative lookahead to accomplish this, I added amp to this so you do not add an extra & in front of an already existing occurrence.

$text = preg_replace('/&(?!#|amp)/', '&', $text);

Regular expression:

&              '&'
(?!            look ahead to see if there is not:
  #            '#'
 |             OR
  amp          'amp'
)              end of look-ahead

See working demo

If you are just trying to replace a small amount of specific strings, use str_replace or strtr

strtr($text, array('&foo' => '&foo'));

Simply /&(?!#)/ will do this (the negative lookahead).

preg_replace('/&(?!#)/', '&', "this &foo and&foo but not &#bar haius&#bar");

Working example: http://regex101.com/r/cB1tW2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM