A 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).
The preg_match_all function returns the number of matches. Third parameter $matches will contain matches in format controlled by flags that can be given in fourth parameter.
If given an array, $matches will contain array in similar format you’d get with preg_match, except that preg_match stops at first match, where preg_match_all iterates over the string until the string is wholly consumed and returns result of each iteration in a multidimensional array, which format can be controlled by the flag in fourth argument.
The fourth argument, $flags, controls structure of $matches array. Default mode is PREG_PATTERN_ORDER and possible flags are PREG_SET_ORDER and PREG_PATTERN_ORDER.
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"
}
}
When the same regexp is run through preg_match, following array is returned:
array(2) {
[0] =>
string(3) "a1b"
[1] =>
string(1) "1"
}