替换模式内的所有实例

Sor*_*anu 9 php regex pcre preg-replace

我有一个像这样的字符串

{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}
Run Code Online (Sandbox Code Playgroud)

我希望它成为

{{ some text ### other text ### and some other text }} @ this should not be replaced {{ but this should: ### }}
Run Code Online (Sandbox Code Playgroud)

我想这个例子很直接,而且我不确定我能更好地解释我想用文字实现的目标.

我尝试了几种不同的方法但没有效果.

cmb*_*ley 9

这可以通过正则表达式回调到简单的字符串替换来实现:

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);
Run Code Online (Sandbox Code Playgroud)

我选择了一个简单的非贪婪的正则表达式来找到你的大括号,但你可以选择改变它以获得性能或满足你的需求.

匿名函数允许您参数化替换:

$find = '@';
$replace = '###';
$output = preg_replace_callback(
    '/{{.+?}}/',
    function($match) use ($find, $replace) {
        return str_replace($find, $replace, $match[0]);
    },
    $input
);
Run Code Online (Sandbox Code Playgroud)

文档:http://php.net/manual/en/function.preg-replace-callback.php