Use the previous trackback as the name of a named capture group

Is there a way to use a backlink to a previous capture group as the name of a named capture group? This may not be possible; if not, this is the correct answer.

Following:

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

Productivity:

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

My attempt to use the backlink for the first capture group as a named capture group (?<$1>.*) Tells me that this is either not possible, or I'm just not doing it right:

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

Productivity:

Warning: preg_match (): Compilation error: unrecognized character after (? <At offset 12

Desired Result:

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

This is simplified with preg_match . When using preg_match_all I usually use:

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

But thought that I could be smoother than that.

+5
source share
2 answers

In short, this is not possible; you can stick with the software tools you have used so far.

Group names (which should consist of 32 alphanumeric and underscores, but must begin with non-digits ) are parsed at compile time, and the value of the backlink is known only at run time. Please note that this is also the reason why you cannot use the backreference inside the lookbehind (you can clearly see that /(x)y[az](?<!\1)/ is ok, the PCRE regex engine sees differently , since it cannot infer the length of lookbehind using the backlink).

+4
source

You already have the answer to the question about regex (no), but for another PHP-based approach, you can try using a callback.

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

Source: https://habr.com/ru/post/1275386/