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