[英]PHP string replace exclude string inside braces
$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);
In the above code, how can we exclude the string inside {{ ... }}. 在上面的代码中,我们如何排除{{...}}中的字符串。 such that the output should be
这样输出应该是
"PHP is a server-side {{scripting language}} designed for {{web development}} but also used as a general-purpose programming english"
Use preg_replace()
instead of str_replace()
: 使用
preg_replace()
代替str_replace()
:
$pattern = sprintf('/{{[^}]+}}(*SKIP)(*F)|%s/', preg_quote($search, '/'));
$new_str = preg_replace($pattern, $replace, $str);
{{[^}]+}}
matches the contents inside {{...}}
block, (*SKIP)(*F)
skips it, and %s
(which is substituted with the escaped search string) matches the required word. {{[^}]+}}
匹配{{...}}
块中的内容, (*SKIP)(*F)
跳过它,而%s
(用转义的搜索字符串替换)匹配所需的单词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.