全域性 RegExp 匹配
一個全域性性的 RegExp 匹配可以用 preg_match_all 進行。preg_match_all 返回主題字串中的所有匹配結果(與 preg_match 相反,preg_match 僅返回第一個)。
preg_match_all 函式返回匹配數。第三個引數 $matches 將包含由可在第四個引數中給出的標誌控制的格式的匹配。
如果給定一個陣列,$matches 將包含與 preg_match 相似的格式的陣列,除了 preg_match 在第一次匹配時停止,其中 preg_match_all 遍歷字串直到字串被完全消耗並返回多維陣列中每次迭代的結果,哪種格式可以由第四個引數中的標誌控制。
第四個引數 $flags 控制 $matches 陣列的結構。預設模式是 PREG_PATTERN_ORDER,可能的標誌是 PREG_SET_ORDER 和 PREG_PATTERN_ORDER。
以下程式碼演示了 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);
PREG_SET_ORDER 的第一個 var_dump 給出了這個輸出:
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 有三個巢狀陣列。每個陣列代表一個匹配,其格式與 preg_match 的返回結果相同。
第二個 var_dump(PREG_PATTERN_ORDER)給出了這個輸出:
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 執行相同的正規表示式時,將返回以下陣列:
array(2) {
[0] =>
string(3) "a1b"
[1] =>
string(1) "1"
}