PCRE 累积匹配组的多次出现

PCRE accumulate multiple occurances of matching group

我想知道这是否可能。我有模式:

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

现在我匹配这个样本:

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

我找到匹配项:

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

但是,是否有可能得到这样的结果:

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

我需要这个来处理多个匹配项,例如asdasdasd {{foo:1381:2:4:7}} {{foo:1111}}.

您可以在 PCRE 正则表达式中使用 \G 在上一场比赛结束后获得多个比赛:

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

RegEx Demo

\G 断言位置在前一个匹配的末尾或第一个匹配的字符串的开头。

示例代码:

$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

输出:

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