Given the following PHP code:
<?php
$str = '/foo/bar/baz';
preg_match('#^(/[^/]+?)*$#', $str, $matches);
var_dump($matches);
…I’m getting the following output:
array (size=2)
0 => string '/foo/bar/baz' (length=12)
1 => string '/baz' (length=4)
…but I don’t understand why. I would expect each match of (/[^/]+?) to be captured into its own group and stuck into $matches, such that it looked like this instead:
array (size=4)
0 => string '/foo/bar/baz' (length=12)
1 => string '/foo' (length=4)
2 => string '/bar' (length=4)
3 => string '/baz' (length=4)
What am I missing?
Edit:
This is the output if I use preg_match_all() instead, which still isn’t what I’m looking for:
array (size=2)
0 =>
array (size=1)
0 => string '/foo/bar/baz' (length=12)
1 =>
array (size=1)
0 => string '/baz' (length=4)
This is the standard behavior of repeated capture groups — they match all the repetitions, but only capture the last one. See Can Regex groups and * wildcards work together? for a similar question using Python. I tried it in Perl and got the same result.