Global RegExp match
suggest changeA global RegExp match can be performed using preg_match_all. preg_match_all returns all matching results in the subject string (in contrast to preg_match, which only returns the first one).
preg_match_all returns the number of matches. The third parameter, $matches, receives those matches. The fourth argument, $flags, controls the shape of that array. The default is PREG_PATTERN_ORDER. The other order flag is PREG_SET_ORDER.
preg_match stops at the first match. preg_match_all continues until the rest of the string cannot match.
Following code demonstrates usage of preg_match_all:
$subject = "a1b c2d3e f4g";
$pattern = '/[a-z]([0-9])[a-z]/';
var_dump(preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER)); // int(3)
var_dump($matches);
preg_match_all($pattern, $subject, $matches); // the flag is PREG_PATTERN_ORDER by default
var_dump($matches);
// And for reference, same regexp run through preg_match()
preg_match($pattern, $subject, $matches);
var_dump($matches);
The first var_dump from PREG_SET_ORDER gives this output:
array(3) {
[0]=>
array(2) {
[0]=>
string(3) "a1b"
[1]=>
string(1) "1"
}
[1]=>
array(2) {
[0]=>
string(3) "c2d"
[1]=>
string(1) "2"
}
[2]=>
array(2) {
[0]=>
string(3) "f4g"
[1]=>
string(1) "4"
}
}
$matches has three nested arrays. Each array represents one match, which has the same format as the return result of preg_match.
The second var_dump (PREG_PATTERN_ORDER) gives this output:
array(2) {
[0]=>
array(3) {
[0]=>
string(3) "a1b"
[1]=>
string(3) "c2d"
[2]=>
string(3) "f4g"
}
[1]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}
}
preg_match returns 1 here and writes the first match to $matches:
array(2) {
[0] =>
string(3) "a1b"
[1] =>
string(1) "1"
}