我有一个字符串:
this &foo and&foo but not &#bar haius&#bar
所有“&foo”都应替换为“&foo”,“bar”应保持不变。 IE。应替换任何 & 后没有 # 的内容。有什么想法吗?
我尝试了以下方法,但效果不是很好......
preg_replace('/&*$[#]*$/', '&', "this &foo and&foo but not &#bar haius&#bar");
感谢您的帮助!
最佳答案
您可以使用否定前瞻来完成此操作,我为此添加了 amp
,这样您就不会在已经存在的事件前面添加额外的 &
。
$text = preg_replace('/&(?!#|amp)/', '&', $text);
正则表达式:
& '&'
(?! look ahead to see if there is not:
# '#'
| OR
amp 'amp'
) end of look-ahead
参见 working demo
如果您只是想替换少量的特定字符串,请使用 str_replace
或 strtr
strtr($text, array('&foo' => '&foo'));
关于php - preg_replace 一个没有跟随特定字符的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405704/