The purpose of a (?(DEFINE)...)
section is only to define named sub-patterns you can use later in the define section itself or in the main pattern. Since these sub-patterns are not defined in the main pattern they don't capture anything, and a reference (?&number)
is only a kind of alias for the sub-pattern \d+
and doesn't capture anything too.
Example with the string: 1abcde2
If I use this pattern: /^(?<num>\d).....(?&num)$/
only 1
is captured in the group num, (?&num)
doesn't capture anything, it's only an alias for \d
.
/^(?<num>\d).....\d$/
produces exactly the same result.
An other point to clarify. With PCRE (the PHP regex engine), a capture group (named or not) can only store one value, even if you repeat it.
The main problem of your approach is that you are trying to do two things at the same time:
- you want to check the format of the string.
- you want to extract an unknown number of items.
Doing this is only possible in particular situations, but impossible in general.
For example, with a flat list like: $list = '10,9,8,7,6,5,4,3,2,1';
where there are no nested elements, you can use a function like preg_match_all
to reuse the same pattern several times in this way:
if (preg_match_all('~\G(\d+)(,|$)~', $list, $matches) && !end($matches[2])) {
// \G ensures that results are contiguous
// you have all the items in $matches[1]
// if the last item of $matches[2] is empty, this means
// that the end of the string is reached and the string
// format is correct
echo '<°)))))))>';
}
Now if you have a nested list like $list = '10,9,(8,(7,6),5),4,(3,2),1';
and you want for example to check the format and to produce a tree structure like:
[ 10, 9, [ 8, [ 7, 6 ], 5 ], 4 , [ 3, 2 ], 1 ]
You can't do it with a single pass. You need one pattern to check the whole string format and an other pattern to extract elements (and a recursive function to use it).
<<<FORGET_THIS_IMMEDIATELY
As an aside you can do it with eval
and strtr
, but it's a very dirty and dangerous way:
eval('$result=[' . strtr($list, '()', '[]') . '];');
FORGET_THIS_IMMEDIATELY;