正則表達式是文本處理的利器,但在 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 |
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);
}
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;
}
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)
function extractUrls(string $text): array {
$pattern = '/https?:\/\/[^\s<>"\']+/i';
preg_match_all($pattern, $text, $matches);
return array_unique($matches[0]);
}
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);
}
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 !== '');
}
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 分
}
(.*)、(.+) 等貪婪量詞,改用 (.*?)、[^"]* 等確定性模式。i 忽略大小寫、m 多行模式、s 單行模式(. 匹配換行)、u UTF-8 模式(處理中文必加)。正則表達式雖強大,但可讀性差、維護成本高。原則:
filter_var、parse_url、mb_split 等內置函數解決的,優先用內置函數。掌握上述高頻模式,配合良好的編碼習慣,即可應對 90% 的 PHP 正則需求。