preg_match_all(
string $pattern,
string $subject,
array &$matches = null,
int $flags = 0,
int $offset = 0
): int|false
結構:$matches[0] = 完整模式匹配陣列,$matches[1] = 第 1 組捕獲群組陣列,$matches[2] = 第 2 組...以此類推
<?php
$html = 'example: this is a test';
preg_match_all('|<[^>]+>(.*)[^>]+>|U', $html, $out, PREG_PATTERN_ORDER);
print_r($out);
/*
Array
(
[0] => Array
(
[0] => example:
[1] => this is a test
)
[1] => Array
(
[0] => example:
[1] => this is a test
)
)
*/
?>
結構:$matches[0] = 第 1 次完整匹配(含所有捕獲群組),$matches[1] = 第 2 次匹配...
<?php
preg_match_all('|<[^>]+>(.*)[^>]+>|U', $html, $out, PREG_SET_ORDER);
print_r($out);
/*
Array
(
[0] => Array
(
[0] => example:
[1] => example:
)
[1] => Array
(
[0] => this is a test
[1] => this is a test
)
)
*/
?>
結構:每個匹配元素變為 [matched_string, offset] 陣列,可與上述兩旗標組合
<?php
preg_match_all('/(\d+)/', 'abc123def456', $out, PREG_OFFSET_CAPTURE);
/*
Array
(
[0] => Array
(
[0] => Array ( [0] => 123 [1] => 3 )
[1] => Array ( [0] => 456 [1] => 9 )
)
[1] => Array
(
[0] => Array ( [0] => 123 [1] => 3 )
[1] => Array ( [0] => 456 [1] => 9 )
)
)
*/
?>
<?php
$text = '聯繫:02-2345-6789 或 0912-345-678 或 (03)1234567';
$pattern = '/(?:\+?886|0)[2-9]\d{7,9}|09\d{8}/';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
// ['02-2345-6789', '0912-345-678', '031234567']
?>
<?php
$html = 'Link';
// 非貪婪匹配屬性值
preg_match_all('/(\w+)="([^"]*)"/', $html, $m, PREG_SET_ORDER);
foreach ($m as $match) {
echo "屬性:{$match[1]} = {$match[2]}\n";
}
// 屬性:href = https://example.com
// 屬性:class = link
// 屬性:data-id = 123
?>
<?php
$md = ' ';
preg_match_all('/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/', $md, $m, PREG_SET_ORDER);
foreach ($m as $match) {
echo "Alt: {$match[1]}, URL: {$match[2]}, Title: {$match[3]}\n";
}
?>
<?php
$csv = 'Name,Age,Note\n"John, Jr.",25,"Likes \"quotes\""\nJane,30,Simple';
preg_match_all('/(?:^|,)(?:"((?:[^"]|"")*)"|([^,]*))/', $csv, $m, PREG_SET_ORDER);
// 需後處理組合欄位,建議實際用 str_getcsv() 或 league/csv
?>
| 陷阱 | 原因 | 解決方案 |
|---|---|---|
| 模式未加定界符 | PHP 要求模式被定界符包裹 | 使用 /pattern/、#pattern#、~pattern~ 等 |
| 貪婪匹配吞噬過多 | .* 預設貪婪 | 使用 .*? 或 U 修飾符(非貪婪模式) |
| 點號不匹配換行 | . 預設不匹配 \n | 加 s 修飾符(DOTALL)或用 [\s\S] |
| 大小寫敏感 | 預設區分大小寫 | 加 i 修飾符 |
| Unicode 字元類別失效 | 預設僅 ASCII | 加 u 修飾符(PCRE_UTF8),使用 \p{L} 等 |
| 效能災難(回溯爆炸) | 巢狀量詞 (a+)+ | 使用具體字元類別、原子群組 (?>...)、具體長度限制 |
/pattern/flags
i - 大小寫不敏感 (PCRE_CASELESS)
m - 多行模式 ^$ 匹配行首尾 (PCRE_MULTILINE)
s - 單行模式 . 匹配換行 (PCRE_DOTALL)
x - 延伸模式 忽略模式空白、允許註解 (PCRE_EXTENDED)
u - UTF-8 模式 (PCRE_UTF8)
U - 非貪婪模式 反轉量詞貪婪性 (PCRE_UNGREEDY)
X - 額外嚴格檢查 (PCRE_EXTRA)
J - 允許重複命名子模式 (PCRE_DUPNAMES)
[^<]* 優於 .*?^pattern$ 減少回溯preg_matchexplode()、JSON 用 json_decode()、HTML 用 DOMDocumentPHP 7.3+ 內建 PCRE2,支援 JIT 編譯(pcre.jit=1 預設開啟)。複雜模式重複執行會自動 JIT 加速。可用 pcre_get_jit_stack() 監控。
preg_match_all 是 PHP 正則提取資料的核心工具。關鍵在於:選對旗標(PATTERN_ORDER vs SET_ORDER)、善用修飾符(特別是 u/s/U)、避免回溯災難、優先考慮專用解析器。掌握這些,能從容應對日誌分析、模板引擎、資料清洗等多樣場景。