Email Address Validation Using Regular Expression

Posted by – December 16, 2011

寫驗證規則最常碰到的就是 email 檢查,每次寫 Regular Expression 都要重新思考一下規則,覺得這樣太浪費時間了,直接寫個筆記給未來的自己複製貼上。

<?php

// 隨便寫幾個 email 來驗證規則
$mails = "someone@gmail.com, _apple@apple.com,
          ex@ex, some-body@gmail.com, NEXTstep@pchome.com.tw, test@nf.NL";
$mails = str_replace(' ', '', strtolower($mails)); // 轉成小寫並去除空白字元
$mails = explode(",",$mails); // 依逗號切斷,並存入陣列
$valid_mails = array();
foreach($mails as $mail){
    if(preg_match("/^[a-z]+[\w\d\.\-_]*@[\w\d-]+\.[\w\.]+[a-z]$/", $mail)){
        array_push($valid_mails, $mail);

        // 可以直接塞進 PHPMailer,省去 $valid_mails 變數
        $phpmailer->mail->AddBCC($mail, '');
    }
}

print_r($valid_mails);
?>

輸出結果如下,不合法的 email 被濾掉了
Array
(
    [0] => someone@gmail.com
    [1] => some-body@gmail.com
    [2] => nextstep@pchome.com.tw
    [3] => test@nf.nl
)

References:

Leave a Reply

Your email address will not be published. Required fields are marked *