註冊、登入、訂閱等功能都需要驗證電子郵件格式。本文提供一個嚴格遵循 RFC 5322 標準的 PHP 驗證函式,比簡單的 filter_var 更精確。
<?php
function is_valid_email_address($email) {
// RFC 5322 官方標準正則組成部分
$qtext = '[^\x0d\x22\x5c\x80-\xff]';
$dtext = '[^\x0d\x5b-\x5d\x80-\xff]';
$atom = '[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+';
$quoted_pair = '\x5c[\x00-\x7f]';
$domain_literal = "\x5b($dtext|$quoted_pair)*\x5d";
$quoted_string = "\x22($qtext|$quoted_pair)*\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\x2e$sub_domain)*";
$local_part = "$word(\x2e$word)*";
$addr_spec = "$local_part\x40$domain";
return (bool) preg_match("!^$addr_spec$!", $email);
}
// 測試範例
$test_emails = [
'user@example.com' => true,
'user.name@domain.co.uk' => true,
'user+tag@example.org' => true,
'"quoted@string"@example.com' => true,
'invalid@' => false,
'@no-local.com' => false,
'spaces here@example.com' => false,
];
foreach ($test_emails as $email => $expected) {
$result = is_valid_email_address($email) ? '通過' : '失敗';
echo "$email => $result (預期: " . ($expected ? '通過' : '失敗') . ")<br>";
}
?>
PHP 5.2+ 內建 filter_var() 即可處理大多數情況:
<?php
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "格式正確";
} else {
echo "格式錯誤";
}
// 進階:檢查 DNS MX 記錄(驗證域名真實存在)
if (filter_var($email, FILTER_VALIDATE_EMAIL) && checkdnsrr(array_pop(explode('@', $email)), 'MX')) {
echo "域名有效";
}
?>
| 方案 | 優點 | 缺點 |
|---|---|---|
| 本文正則函式 | 嚴格符合 RFC 5322,支援引用字串、註解等複雜格式 | 效能較差,程式碼冗長難維護 |
| filter_var() | 內建、效能好、程式碼簡潔 | 允許部分技術合法但實務罕見的格式 |
| 簡單正則 | 效能最好、易自訂 | 易漏判或誤判邊界案例 |
一般 Web 專案推薦使用 filter_var() 搭配前端 HTML5 type="email" 雙重驗證;只有郵件系統核心模組才需要完整 RFC 合規驗證。