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

时间:2013-12-05 16:43:05

标签: php regex

我有一个字符串:

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

所有“& foo”应替换为“& amp; foo”,而“& #bar”应保持不变。即任何&没有#应该被替换。有什么想法吗?

我尝试过以下但是效果不是很好......

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

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

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

正则表达式:

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

请参阅working demo

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

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

答案 1 :(得分:0)

只需/&(?!#)/即可(负面预测)。

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

工作示例:http://regex101.com/r/cB1tW2