首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 常用正則表達式速查手冊(含實戰場景)

     編輯:PHP 相關知識

前言

正則表達式是文本處理的利器,但在 PHP 開發中常因語法複雜、調試困難而被邊緣化。本文整理了高頻使用場景的正則模式,並附帶 preg_match、preg_replace 實戰代碼,助你快速解決表單驗證、數據清洗、內容提取等問題。

核心語法速查表

元字符說明示例
.匹配任意單字符(除換行符)a.c 匹配 "abc", "aac"
\d數字 [0-9]\d{11} 匹配 11 位手機號
\w字母數字下劃線 [a-zA-Z0-9_]\w+@\w+\.\w+ 簡易郵箱
\s空白字符(空格、制表、換行)\s+ 匹配多個空格
^字符串開始^https?:// 匹配協議頭
$字符串結束\.php$ 匹配 PHP 文件
*零次或多次ab*c 匹配 "ac", "abc", "abbc"
+一次或多次\d+ 至少一位數字
?零次或一次https?:// s 可選
{n,m}n 到 m 次\d{6,8} 6-8 位數字
[]字符集合[a-f0-9] 十六進制字符
[^]排除字符集合[^<>]* 非標簽內容
()分組捕獲(\d{4})-(\d{2}) 捕獲年月
|或邏輯cat|dog 匹配貓或狗
(?P)命名捕獲組 (PHP 支持)(?P\d{4})

高頻實戰場景與代碼

1. 手機號驗證(中國大陸)

function isValidMobile(string $mobile): bool {
    // 支持三大運營商最新號段,嚴格模式
    $pattern = '/^1(?:3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/';
    return (bool)preg_match($pattern, $mobile);
}

2. 身份證號碼(18 位)

function isValidIdCard(string $id): bool {
    $pattern = '/^[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/';
    if (!preg_match($pattern, $id)) return false;
    // 校驗碼驗證(省略,生產環境必加)
    return true;
}

3. 郵箱地址(RFC 5322 簡化版)

function isValidEmail(string $email): bool {
    $pattern = '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/';
    return (bool)preg_match($pattern, $email);
}
// 生產建議:使用 filter_var($email, FILTER_VALIDATE_EMAIL)

4. URL 鏈接提取

function extractUrls(string $text): array {
    $pattern = '/https?:\/\/[^\s<>"\']+/i';
    preg_match_all($pattern, $text, $matches);
    return array_unique($matches[0]);
}

5. HTML 標簽清理(保留安全標簽)

function stripTagsSafe(string $html, array $allowed = ['p','br','strong','em','a']): string {
    $allowedPattern = implode('|', array_map('preg_quote', $allowed));
    $pattern = '/<\/?(?!(?:' . $allowedPattern . ')\b)[^>]+>/i';
    return preg_replace($pattern, '', $html);
}

6. 中文分詞輔助(按標點/數字/字母分割)

function splitChineseText(string $text): array {
    $pattern = '/([\x{4e00}-\x{9fa5}]+|[a-zA-Z0-9]+|[,。!?、;:“”‘’()【】《》])/u';
    preg_match_all($pattern, $text, $matches);
    return array_filter($matches[0], fn($s) => $s !== '');
}

7. 密碼強度檢測(至少 8 位,含大小寫、數字、特殊字符)

function checkPasswordStrength(string $pwd): int {
    $score = 0;
    $score += (bool)preg_match('/[a-z]/', $pwd);
    $score += (bool)preg_match('/[A-Z]/', $pwd);
    $score += (bool)preg_match('/\d/', $pwd);
    $score += (bool)preg_match('/[^a-zA-Z0-9]/', $pwd);
    $score += (strlen($pwd) >= 12) ? 1 : 0;
    return $score; // 0-5 分
}

調試技巧與性能提示

  • 使用在線調試工具:regex101 支持 PHP 風味,可視化解釋每一步匹配。
  • 避免災難性回溯:慎用 (.*)、(.+) 等貪婪量詞,改用 (.*?)、[^"]* 等確定性模式。
  • 預編譯複用:同一正則在循環中多次使用時,PHP 會自動緩存編譯結果,但跨請求無法復用。長運行腳本可考慮將 Pattern 存入靜態變量。
  • 修飾符選擇:i 忽略大小寫、m 多行模式、s 單行模式(. 匹配換行)、u UTF-8 模式(處理中文必加)。

總結

正則表達式雖強大,但可讀性差、維護成本高。原則:

  1. 能用 filter_var、parse_url、mb_split 等內置函數解決的,優先用內置函數。
  2. 業務邏輯複雜的驗證,封裝為單獨函數/類,附帶完整單元測試用例。
  3. 複雜文本解析(如 HTML、JSON、XML)務必使用專用解析器(DOMDocument, JSONDecoder, XMLReader),切勿用正則解析結構化文檔。

掌握上述高頻模式,配合良好的編碼習慣,即可應對 90% 的 PHP 正則需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved