替换模式中的所有事件 [英] Replace all occurrences inside pattern
问题描述
我有一个像这样的字符串
I have a string that is like this
{{ 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: ### }}
我想这个例子很简单,我不确定我能不能用言语更好地解释我想要实现的目标.
I guess the example is straight forward enough and I'm not sure I can better explain what I want to to achieve in words.
我尝试了几种不同的方法,但是都没有用.
I tried several different approaches but none worked.
推荐答案
这可以通过使用正则表达式调用简单的字符串replace来实现:
This can be achieved with a regular expression calling back to a simple string replace:
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);
我选择了一个简单的非贪婪的正则表达式来查找括号,但是您可以选择更改此括号以提高性能或满足您的需求.
I have opted for a simple non-greedy regular expression to find your braces but you may choose to alter this for performance or to suit your needs.
匿名函数使您可以参数化替换项:
Anonymous functions would allow you to parameterise your replacements:
$find = '@';
$replace = '###';
$output = preg_replace_callback(
'/{{.+?}}/',
function($match) use ($find, $replace) {
return str_replace($find, $replace, $match[0]);
},
$input
);
文档: http://php.net/manual/zh/function.preg-replace-callback.php
这篇关于替换模式中的所有事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!