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

时间:2018-02-15 21:41:18

标签: php regex pcre regex-group backreference

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

以下内容:

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

收率:

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

我尝试使用第一个捕获组作为命名捕获组(?<$1>.*)的反向引用告诉我它不可能或我只是没有正确执行:

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

收率:

  

警告:preg_match():编译失败:无法识别的字符(?&lt; at offset 12

期望的结果是:

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

使用preg_match简化了这一过程。使用preg_match_all时,我通常使用:

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

但是我觉得我可能比那更光滑。

2 个答案:

答案 0 :(得分:4)

简而言之,这是不可能的,你可以坚持到目前为止一直使用的编程手段。

在编译时解析组名(应该consist of up to 32 alphanumeric characters and underscores, but must start with a non-digit),并且只在运行时知道反向引用值。请注意,这也是为什么你不能在lookbehind中使用反向引用的原因(尽管你清楚地看到/(x)y[a-z](?<!\1)/是正常的,PCRE regex engine sees otherwise,因为它无法通过反向引用来推断lookbehind的长度。)< / p>

答案 1 :(得分:2)

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

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