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

4

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

以下内容:

$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():编译失败:在偏移量12处的(?<后面有无法识别的字符

期望的结果应该是:

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

使用 preg_match 进行了简化。当使用 preg_match_all 时,我通常使用以下代码:

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

But thought I might be slicker than that.

2个回答

5
简而言之,不可能实现,你可以继续使用到目前为止使用的编程方法。
组名(必须由最多32个字母数字字符和下划线组成,但必须以非数字开头)在编译时解析,回溯引用值仅在运行时才知道。请注意,这也是您无法在后向查找中使用回溯引用的原因(尽管您清楚地看到/(x)y[a-z](?<!\1)/是可以的,但PCRE正则表达式引擎看到了不同的内容,因为它无法推断具有回溯引用的后向查找的长度)。

3

你已经得到了正则表达式问题的答案(否),但是对于另一种基于PHP的方法,你可以尝试使用回调函数。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接