preg_replace_callback 奇怪的行为

preg_replace_callback strange behaviour

我无法理解为什么 preg_replace_callback 会这样处理模式

    $article = "{{test1}} {{test2}}";

    $article = preg_replace_callback('{{(.*?)}}', 'handlePattern', $article);

    function handlePattern($matches) {
        echo "matches = " . print_r($matches, true);

    }

并打印出这个结果

    matches = Array
(
    [0] => {{test1}
    [1] => {test1
)
matches = Array
(
    [0] => {{test2}
    [1] => {test2
)

但我希望它必须是这样的

matches = Array
(
    [0] => {{test1}}
    [1] => test1
)
matches = Array
(
    [0] => {{test2}}
    [1] => test2
)

如何获取{{ }}中的内容?

在以下表达式中,外部花括号被解释为正则表达式 delimiters

'{{(.*?)}}'

实际上您可以使用任何定界符。例如,以下具有相同的效果:

'/{(.*?)}/'

所以你应该在表达式中使用定界符,例如:

'/{{(.*?)}}/'

此外,您应该引用花括号,因为在某些序列中它们可以被解释为特殊的正则表达式字符:

'/\{\{(.*?)\}\}/'

可以通过preg_quote函数获得特定定界符的字符转义版本:

echo preg_quote('{', '/'); // \{

您正在使用正则表达式搜索,这需要您使用 PCRE syntax.

声明模式

您的模式 '{{(.*?)}}'{ 开始,}。 PCRE 将它们视为模式的开始和结束。因此,它们从要匹配的模式中被忽略。您需要用额外的引号字符引用模式才能使其工作。

例如,

function handlePattern($matches) {
   echo "matches = " . print_r($matches, true);
}

$article = "{{test1}} {{test2}}";
$article = preg_replace_callback('/{{(.*?)}}/', 'handlePattern', $article);

请注意,我已将 '{{(.*?)}}' 更改为 '/{{(.*?)}}/'

结果:

matches = Array
(
    [0] => {{test1}}
    [1] => test1
)
matches = Array
(
    [0] => {{test2}}
    [1] => test2
)