PHP preg_replace()带有一对大括号,但忽略带有3的大括号

时间:2013-12-05 01:50:48

标签: php regex preg-replace

想知道这是否可能

$c = "The color {{ white }} will become {{ white }}.";

$c = preg_replace("#{{\s*white\s*}}#", "black", $c);

结果将是

The color black will become black.

如果附加了{和}或任何其他字符,是否有办法忽略它,所以

$c = "The color {{{ white }}} will become {{ white }}.";

将成为

The color {{ white }} will become black.

谢谢。

2 个答案:

答案 0 :(得分:4)

使用negative lookahead

$c = preg_replace("#{{(?!{)\s*white\s*}}(?!})#", "black", $c);

Demo.

答案 1 :(得分:0)

试试这个正则表达式/\{{2,3}\s*white\s*\}{2,3}/。这是你的例子。

$c = "The color {{{ white }}} will become {{ white }}.";

echo preg_replace("/\{{2,3}\s*white\s*\}{2,3}/", "black", $c);

\{\}表示括号。并且{2,3}表示它应该匹配2或3个括号。