Search code examples
phpregexpcre

Php preg_match_all matches only last element


I've this regex

{{([ a-zA-Z0-9_\-]+)\s*(?:\[([ a-zA-Z0-9_\-]+)\]\s*)*}}

and i need to match strings such as:

{{word with spaces}}
{{word with spaces [sub1]}}
{{word with spaces   [sub1]  [sub 2]  [Sub-3] }}

capturing word with spaces, and sub1, sub 2, Sub-3.

The regex is working but the for the sub-s string matching gives only the last match, i.e. Sub-3. How to get all sub1, sub 2, Sub-3? Thanks


Solution

  • Here is another variant using \G that is bit faster and avoids empty matches:

    (?:{{([\w-]+(?:\h+[\w-]+)*)|(?!\A)\G)(?:\h*\[([^]]+)]|\h*}})
    

    RegEx Demo

    \G asserts position at the end of the previous match or the start of the string for the first match.