My script is simple:
<?php
$str = "mem: 9 334 23423343 3433434";
$num_matches = preg_match_all("/^mem:(\s+\d+)+$/", $str, $matches);
if (!$num_matches) {
throw new Exception("no match");
}
echo "$num_matches matches\n";
var_dump($matches);
I was expecting that the pattern (\s+\d+)+
should match all of the numbers in $str
but the output only shows the last match for some reason:
1 matches
array(2) {
[0] =>
array(1) {
[0] =>
string(27) "mem: 9 334 23423343 3433434"
}
[1] =>
array(1) {
[0] =>
string(8) " 3433434"
}
}
As you can see, $matches[1]
contains only the last \s+\d+
occurrence in $str
. I was expecting it should contain all of the matches: 9, 334, 23423343, 343434
.
Is there some way to alter my pattern such that it returns all of these numbers for a string that may contain an arbitrary number of strings? Am I correct in thinking this is incorrect behavior by preg_match_all? Should I report it to the PHP devs?
EDIT: according to the docs, the default flag of PREG_PATTERN_ORDER:
Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.