萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP preg_match_all 完整指南:模式排序旗標、偏移捕獲、實戰範例詳解

preg_match_all 核心語法與旗標

preg_match_all(
    string $pattern,
    string $subject,
    array &$matches = null,
    int $flags = 0,
    int $offset = 0
): int|false

三大排序旗標深度解析

1. PREG_PATTERN_ORDER(預設)

結構:$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 ) ) */ ?>

2. PREG_SET_ORDER

結構:$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 ) ) */ ?>

3. PREG_OFFSET_CAPTURE

結構:每個匹配元素變為 [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 )
        )
)
*/
?>

實戰範例集錦

範例 1:提取所有電話號碼(多種格式)

<?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']
?>

範例 2:解析 HTML 標籤屬性(貪婪 vs 非貪婪)

<?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
?>

範例 3:提取 Markdown 圖片連結

<?php
$md = '![Logo](logo.png) ![Banner](https://cdn.example.com/banner.jpg "Title")';
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";
}
?>

範例 4:解析 CSV 行(處理引號內逗號)

<?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)

效能優化技巧

  1. 避免在循環中重複編譯:將模式預編譯或移出循環
  2. 使用具體字元類別:[^<]* 優於 .*?
  3. 錨定開頭結尾:^pattern$ 減少回溯
  4. 大量資料用 preg_match_all 一次性匹配:優於循環 preg_match
  5. 考慮替代方案:簡單分割用 explode()、JSON 用 json_decode()、HTML 用 DOMDocument

PCRE 版本與 JIT

PHP 7.3+ 內建 PCRE2,支援 JIT 編譯(pcre.jit=1 預設開啟)。複雜模式重複執行會自動 JIT 加速。可用 pcre_get_jit_stack() 監控。

總結

preg_match_all 是 PHP 正則提取資料的核心工具。關鍵在於:選對旗標(PATTERN_ORDER vs SET_ORDER)、善用修飾符(特別是 u/s/U)、避免回溯災難、優先考慮專用解析器。掌握這些,能從容應對日誌分析、模板引擎、資料清洗等多樣場景。

copyright © 萬盛學電腦網 all rights reserved