php - preg_replace一个字符后面没有特定字符

hob*_*ley 2 php regex

我有一个字符串:

this &foo and&foo but not &#bar haius&#bar
Run Code Online (Sandbox Code Playgroud)

所有"&foo"应该替换为"& foo",而"&#bar"应保持不变.即任何&未跟随#应该被替换.有任何想法吗?

我试过以下但是进展不顺利......

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

谢谢你的帮助!

hwn*_*wnd 5

您可以使用负向前瞻来完成此操作,我添加amp了这个,因此您不会&在已存在的事件前添加额外的内容.

$text = preg_replace('/&(?!#|amp)/', '&', $text);
Run Code Online (Sandbox Code Playgroud)

正则表达式:

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

看到 working demo

如果您只是尝试替换少量特定字符串,请使用str_replacestrtr

strtr($text, array('&foo' => '&foo'));
Run Code Online (Sandbox Code Playgroud)