PCRE accumulate multiple occurances of matching group

145 Views Asked by At

I wonder if this is possible. I have the pattern:

foo:(?<id>\d+)(?::(?<srcid>\d+))*

Now I match on this specimen:

asdasdasd {{foo:1381:2:4:7}}

I get the match:

Full match      `foo:1381:2:4:7`
Group `id`      `1381`
Group `srcid`   `7`

However, is it possible to get a result such as:

Full match      `foo:1381:2:4:7`
Group `id`      `1381`
Group `srcid`   [`2`, `4`, `7`]

I need this to work with multiple matches, e.g. asdasdasd {{foo:1381:2:4:7}} {{foo:1111}}.

1

There are 1 best solutions below

1
On BEST ANSWER

You can use \G in your PCRE regex to get multiple matches after end of previous match:

(?:{{foo:(?<id>\d+)|(?<!^)\G)(?::(?<srcid>\d+)|}})

RegEx Demo

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

Sample Code:

$str = 'asdasdasd {{foo:1381:2:4:7}}';
preg_match_all('/(?:foo:(?<id>\d+)|(?<!^)\G):(?<srcid>\d+)/', $str, $m);

print_r($m['srcid']);
echo $m['id'][0]; // 1381

Output:

Array
(
    [0] => 2
    [1] => 4
    [2] => 7
)
1381