正則表達式是字串驗證、擷取、替換的利器。本文精選 7 個實戰高頻場景,提供可直接使用的 PHP 代碼與模式解析,涵蓋 filter_var 內建驗證與 preg_match/preg_replace 進階用法。
$email = 'test+email@ansoncheung.tk';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Your email is ok.";
} else {
echo "Wrong email address format.";
}
優勢:內建支援 RFC 5322 標準、處理邊界情況(如 + 標籤、子網域)、無需維護複雜正則、效能優於自寫正則。
$username = "user_name12";
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
echo "Your username is ok.";
} else {
echo "Wrong username format.";
}
^ $:錨定開頭結尾,防止部分匹配[a-z\d_]:英文、數字、底線{5,20}:長度限制i:不區分大小寫$IP = "198.168.1.78";
if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $IP)) {
echo "Your IP address is ok.";
} else {
echo "Wrong IP address.";
}
模式拆解:([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) 匹配 0-255,\. 匹配點號,{3} 重複三段,最後一段無點號。
$zipcode = "12345-5434";
if (preg_match('/^([0-9]{5})(-[0-9]{4})?$/i', $zipcode)) {
echo "Your Zip code is ok.";
} else {
echo "Wrong Zip code.";
}
$url = "https://ansoncheung.tk/";
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
echo "Your url is ok.";
} else {
echo "Wrong url.";
}
注意:此正則驗證結構而非可達性。生產環境建議搭配 filter_var($url, FILTER_VALIDATE_URL) 或 parse_url() 解析後再驗證。
$url = "https://ansoncheung.tk/articles";
preg_match('@^(?:https://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
echo $host; // 輸出: ansoncheung.tk
@...@:使用 @ 為定界符,避免 URL 中斜線衝突(?:https://)?:非捕獲群組,可選協定前綴([^/]+):捕獲非斜線字符(主機名)$text = "Sample sentence from AnsonCheung.tk, regular expression has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp...)";
$text = preg_replace('/\b(regex)\b/i', '$1', $text);
echo $text;
\b:單字邊界,避免部分匹配(如 "regexp" 不會被高亮)$1:回參考第 1 捕獲群組,保持原大小寫<mark> 標籤語意化高亮,可搭配 CSS 樣式| 場景 | 建議做法 |
|---|---|
| Email、URL、IP 基礎驗證 | 優先使用 filter_var() 內建過濾器 |
| 複雜業務規則 | 撰寫正則,加上 x 修飾符支援註解與換行 |
| 高頻呼叫 | 預編譯正則模式、避免在迴圈中重複建構 |
| 大量文字處理 | 考慮 preg_replace_callback() 或非正則替代方案 |