PHP字符串替换括号内的排除字符串

时间:2014-08-13 20:20:44

标签: php regex

$str = "PHP is a server-side {{scripting language}} designed for {{web development}} but also used as a general-purpose programming language";
$search = 'language';
$replace = 'english';

$new_str = str_replace($search, $replace, $str);

在上面的代码中,我们如何排除{{...}}中的字符串。这样输出应该是

"PHP is a server-side {{scripting language}} designed for {{web development}} but also used as a general-purpose programming english"

1 个答案:

答案 0 :(得分:3)

使用preg_replace()代替str_replace()

$pattern = sprintf('/{{[^}]+}}(*SKIP)(*F)|%s/', preg_quote($search, '/'));
$new_str = preg_replace($pattern, $replace, $str);

{{[^}]+}}匹配{{...}}块内的内容,(*SKIP)(*F)跳过它,%s(用转义的搜索字符串替换)与所需的字匹配。

Demo