The $match[0]
, $match[1]
, etc., items are not the individual matches, they're the "captures".
Regardless of how many matches there are, the number of entries in $matches
is constant, because it's based on what you're searching for, not the results. There's always at least one entry, plus one more for each pair of capturing parentheses in the search pattern.
For example, if you do:
$matches = array();
$search = preg_match_all("/\D+(\d+)/", "a1b12c123", $matches);
print_r($matches);
Matches will have only two items, even though three matches were found. $matches[0]
will be an array containing "a1", "b12" and "c123" (the entire match for each item) and $matches[1]
will contain only the first capture for each item, i.e., "1", "12" and "123".
I think what you want is something more like:
foreach ($matches[1] as $match) {
echo $match;
}
Which will print out the first capture expression from each matched string.