我有一个像这样的字符串
{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}
我希望它成为
{{ some text ### other text ### and some other text }} @ this should not be replaced {{ but this should: ### }}
我想这个例子很直接,我不确定我能更好地解释我想要用语言实现的目标.
这可以通过正则表达式回调到简单的字符串替换来实现:
原文链接:https://www.f2er.com/php/137549.htmlfunction replaceInsideBraces($match) { return str_replace('@','###',$match[0]); } $input = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}'; $output = preg_replace_callback('/{{.+?}}/','replaceInsideBraces',$input); var_dump($output);
我选择了一个简单的非贪婪的正则表达式来找到你的大括号,但你可以选择改变它以提高性能或满足你的需要.
匿名函数允许您参数化替换:
$find = '@'; $replace = '###'; $output = preg_replace_callback( '/{{.+?}}/',function($match) use ($find,$replace) { return str_replace($find,$replace,$match[0]); },$input );
文档:http://php.net/manual/en/function.preg-replace-callback.php