替换模式内出现的所有实例


Replace all occurrences inside pattern

我有一个这样的字符串

{{ 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: ### }}

我想这个例子足够直截了当,我不确定我能更好地用语言解释我想要实现的目标。

我尝试了几种不同的方法,但没有一种奏效。

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

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);

我选择了一个简单的非贪婪正则表达式来找到您的大括号,但您可以选择更改它以提高性能或满足您的需求。

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

$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

您可以使用 2 个正则表达式来完成。第一个选择{{}}之间的所有文本,第二个@替换为###。使用 2 个正则表达式可以像这样完成:

$str = preg_replace_callback('/first regex/', function($match) {
    return preg_replace('/second regex/', '###', $match[1]);
});

现在您可以制作第一个和第二个正则表达式,自己尝试一下,如果您不明白,请在这个问题中提出来。

另一种方法是使用正则表达式('{'{[^}]+?)@([^}]+?'}'})。您需要多次运行它以匹配{{大括号内的多个@ }}

<?php
$string = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}';
$replacement = '#';
$pattern = '/('{'{[^}]+?)@([^}]+?'}'})/';
while (preg_match($pattern, $string)) {
    $string = preg_replace($pattern, "$1$replacement$2", $string);
}
echo $string;

哪些输出:

{

{ 一些文本 ### 其他文本 ### 和其他一些文本 }} @ 这应该 不被替换{{,但这应该:### }}