Search code examples
phpregexpreg-replace-callback

preg_replace_callback strange behaviour


I can't understand why preg_replace_callback handle pattern like this

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

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

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

    }

And it prints this result

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

But I expect that it have to be like this

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

How can I get the content inside {{ }}?


Solution

  • In the following expression the outer curly braces are interpreted as regular expression delimiters

    '{{(.*?)}}'

    You could use any delimiter actually. For instance, the following has the same effect:

    '/{(.*?)}/'

    So you should use delimiters in your expression, e.g.:

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

    Also, you should quote the curly braces, because in certain sequences they can be interpreted as special regular expression characters:

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

    An escaped version of a character for specific delimiter can be obtained by means of preg_quote function:

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