使用先前的反向引用作为命名捕获组的名称

Use previous backreference as name of named capture group

有没有办法使用对先前捕获组的反向引用作为命名捕获组的名称?这可能是不可能的,如果不是,那就是一个有效的答案。

以下:

$data = 'description: some description';
preg_match("/([^:]+): (.*)/", $data, $matches);
print_r($matches);

产量:

(
    [0] => description: some description
    [1] => description
    [2] => some description
)

我尝试使用对第一个捕获组的反向引用作为命名捕获组 (?<>.*) 告诉我这是不可能的,或者我只是没有正确地做:

preg_match("/([^:]+): (?<>.*)/", $data, $matches);

产量:

Warning: preg_match(): Compilation failed: unrecognized character after (?< at offset 12

期望的结果是:

(
    [0] => description: some description
    [1] => description
    [description] => some description
)

这是使用 preg_match 简化的。使用 preg_match_all 时,我通常使用:

$matches = array_combine($matches[1], $matches[2]);

但我想我可能比那更圆滑。

总之,不可能,你可以坚持你目前使用的编程方式。

组名称(应该 consist of up to 32 alphanumeric characters and underscores, but must start with a non-digit) are parsed at compile time, and a backreference value is only known at run-time. Note it is also a reason why you cannot use a backreference inside a lookbehind (altghough you clearly see that /(x)y[a-z](?<!)/ is OK, the PCRE regex engine sees otherwise 因为它无法通过反向引用推断后视的长度)。

您已经找到了正则表达式问题的答案(否),但是对于基于 PHP 的不同方法,您可以尝试使用回调。

preg_replace_callback($pattern, function($match) use (&$matches) {
    $matches[$match[1]] = $match[2];
}, $data);