I am experimenting with the named subpattern/'subroutine' regex features in PHP's PCRE and I'm hoping someone can explain the following strange output:
$re = "/
(?(DEFINE)
(?<a> a )
)
^(?&a)$
/x";
var_dump(preg_match($re, 'a', $match)); // (int) 1 as expected
var_dump($match); // Array( [0] => 'a' ) <-- Why?
I can't understand why the named group "a" is not in the result (with the contents "a"). Changing preg_match
to preg_match_all
puts "a" and "1" in the match data but both contain only an empty string.
I really like the idea of writing regular expressions this way, as you can make them incredibly powerful whilst keeping them very maintainable (see this answer for a good example of this), however if the subpatterns are not available in the match data then it's not much use really.
Am I missing something here or should I just mourn what could have been and move on?