PHP 採用 Perl 兼容正則表達式 (PCRE),提供 preg_match()、preg_match_all()、preg_replace()、preg_split() 等核心函數。本文重點解析匹配類函數的差異與實戰技巧。
/pattern/、#pattern#、~pattern~/、#、%/http:\/\// 或改用 #https://#int preg_match(string $pattern, string $subject, array &$matches = null)
1 (匹配)、0 (不匹配)、false (錯誤)$matches[0]:完整匹配內容;$matches[1]:第一個捕獲組...以此類推<?php
if (preg_match("/php/i", "PHP is the web scripting language", $matches)) {
echo "找到: " . $matches[0]; // 輸出: PHP
} else {
echo "未找到";
}
<?php
preg_match("/^(http:\/\/)?([^\/]+)/i", "https://www.jb51.net/index.html", $matches);
$host = $matches[2]; // www.jb51.net
preg_match("/[^\.]+\.[^\.]+$/", $host, $matches);
echo "域名: {$matches[0]}"; // 輸出: jb51.net
int preg_match_all(string $pattern, string $subject, array &$matches, int $flags = PREG_PATTERN_ORDER)
false$matches 結構:| 旗標 | 結構說明 | 適用場景 |
|---|---|---|
PREG_PATTERN_ORDER (預設) | $matches[0] 全部完整匹配;$matches[1] 第一個捕獲組所有匹配... | 提取特定捕獲組所有值 |
PREG_SET_ORDER | $matches[0] 第一組所有捕獲;$matches[1] 第二組... | 逐組處理(如替換每個匹配) |
PREG_OFFSET_CAPTURE | 每個結果包含 [匹配內容, 位移] | 需知道匹配位置 |
| 編碼 | 正則模式 | 說明 |
|---|---|---|
| GBK/GB2312 | /[\x80-\xff]+/ 或 /[\xa1-\xff]+/ | 雙位元組中文範圍 |
| UTF-8 | /[\x{4e00}-\x{9fa5}]+/u | Unicode CJK 統一表意文字區塊,需 u 修飾符 |
<?php
$str = "學習php是一件快樂的事。";
// GBK 環境
preg_match_all("/[\x80-\xff]+/", $str, $match);
// UTF-8 環境
preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $str, $match);
print_r($match);
/* 輸出:
Array (
[0] => Array (
[0] => 學習
[1] => 是一件快樂的事。
)
)
*/
strpos()、str_replace()、explode() 等原生函數掌握 preg_match 與 preg_match_all 的核心差異(單次 vs 全局)、捕獲組結構、旗標應用,能高效解決 90% 的字串提取需求。