【发布时间】:2018-02-15 21:41:18
【问题描述】:
有没有办法使用对前一个捕获组的反向引用作为命名捕获组的名称?这可能是不可能的,如果不是,那么这是一个有效的答案。
以下内容:
$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(): 编译失败: (? 之后的字符无法识别
期望的结果是:
(
[0] => description: some description
[1] => description
[description] => some description
)
这使用preg_match 进行了简化。使用preg_match_all时我通常使用:
$matches = array_combine($matches[1], $matches[2]);
但我想我可能比那更狡猾。
【问题讨论】:
标签: php regex pcre regex-group backreference