Search code examples
phpregexpreg-replace-callback

PHP preg_replace_callback catch more than one occurance in line


I search for custom HTML tags with:

$match = preg_replace_callback("/<tag>(.*)<tag>/", function ($key) {
    $result = getTxt($key[1]);

    return $result;
}, $buffer);

It works when input is:

Abc <tag>1<tag> efg

But why it returns null on:

Abc <tag>2<tag> ef <tag>3<tag> h

I've tried to group nongreedy ending tag: /$tag(.*)($tag?)/ with same result.


Solution

  • You need to make the .* non greedy via .*?

    /<tag>(.*?)<tag>/
    

    Say $tag is <tag>, that means $tag? becomes <tag>? which captures <tag and <tag>