Php 使用上一个反向引用作为命名捕获组的名称
有没有一种方法可以使用对先前捕获组的反向引用作为命名捕获组的名称?这可能不可能,如果不可能,那么这是一个有效的答案 以下是:Php 使用上一个反向引用作为命名捕获组的名称,php,regex,pcre,regex-group,backreference,Php,Regex,Pcre,Regex Group,Backreference,有没有一种方法可以使用对先前捕获组的反向引用作为命名捕获组的名称?这可能不可能,如果不可能,那么这是一个有效的答案 以下是: $data = 'description: some description'; preg_match("/([^:]+): (.*)/", $data, $matches); print_r($matches); 收益率: ( [0] => description: some description [1] => description
$data = 'description: some description';
preg_match("/([^:]+): (.*)/", $data, $matches);
print_r($matches);
收益率:
(
[0] => description: some description
[1] => description
[2] => some description
)
我尝试将第一个捕获组的反向引用用作命名的捕获组(?*)
,这表明这是不可能的,或者我做得不正确:
preg_match("/([^:]+): (?<$1>.*)/", $data, $matches);
使用preg\u match
可简化此操作。使用preg\u match\u all
时,我通常使用:
$matches = array_combine($matches[1], $matches[2]);
但我认为我可能比这更圆滑。简而言之,这是不可能的,你可以坚持你迄今为止一直使用的编程方法
组名(应该是)在编译时被解析,而反向引用值只有在运行时才知道。请注意,这也是您不能在lookback中使用backreference的原因之一(尽管您清楚地看到
/(x)y[a-z](?是可以的,因为它不能通过backreference推断lookback的长度)。您已经对regex问题(否)有了答案,但是对于不同的基于PHP的方法,您可以尝试使用回调
preg_replace_callback($pattern, function($match) use (&$matches) {
$matches[$match[1]] = $match[2];
}, $data);
preg_replace_callback($pattern, function($match) use (&$matches) {
$matches[$match[1]] = $match[2];
}, $data);