電子郵件驗證是 Web 開發中的常見需求。本文提供多種正則模式,從基礎到嚴格,並附帶可直接使用的 PHP 驗證函數與提取函數。
| 模式 | 特點 | 適用場景 |
|---|---|---|
/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$/i | 基礎驗證,支援多級域名 | 一般表單驗證 |
/^[a-z]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?$/i | 嚴格模式,符合 RFC 標準,支援 .com.cn 等雙級後綴 | 高安全性需求 |
function is_valid_email($email, $test_mx = false) {
$pattern = "/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i";
if (preg_match($pattern, $email)) {
if ($test_mx) {
list($username, $domain) = explode("@", $email);
return getmxrr($domain, $mxrecords);
}
return true;
}
return false;
}
function getEmails($str) {
$pattern = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
preg_match_all($pattern, $str, $matches);
return $matches[0];
}
// 示例
$text = "聯繫我們: admin@example.com, support@test.com.cn";
$emails = getEmails($text);
print_r($emails);
^ / $:字串開頭/結尾錨點+:前一字元出現 1 次或多次{2,3}:前一字元出現 2~3 次[]:字元集合,如 [a-z0-9] 表示字母或數字\.:轉義點號,匹配實際的「.」i 修飾符:不區分大小寫type="email" 做初步攔截。filter_var($email, FILTER_VALIDATE_EMAIL) 雙重驗證。