PHP email validation

This question already has an answer here:

  • How to validate an email address using a regular expression? 74 answers

  • I suggest you use the FILTER_VALIDATE_EMAIL filter:

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        //valid
    }
    

    You can also use its regular expression directly:

    "/^(?!(?:(?:x22?x5C[x00-x7E]x22?)|(?:x22?[^x5Cx22]x22?)){255,})(?!(?:(?:x22?x5C[x00-x7E]x22?)|(?:x22?[^x5Cx22]x22?)){65,}@)(?:(?:[x21x23-x27x2Ax2Bx2Dx2F-x39x3Dx3Fx5E-x7E]+)|(?:x22(?:[x01-x08x0Bx0Cx0E-x1Fx21x23-x5Bx5D-x7F]|(?:x5C[x00-x7F]))*x22))(?:.(?:(?:[x21x23-x27x2Ax2Bx2Dx2F-x39x3Dx3Fx5E-x7E]+)|(?:x22(?:[x01-x08x0Bx0Cx0E-x1Fx21x23-x5Bx5D-x7F]|(?:x5C[x00-x7F]))*x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))]))$/iD"
    

    But in that case, if a bug is found in the regular expression, you'll have to update your program instead of just updating PHP.


    Unless you want to use a very very long regular expressions you'll run into valid email addresses that are not covered (think Unicode). Also fake email addresses will pass as valid, so what is the point of validating if you can simply write test@test.com and get away with it?

    The best way to validate email addresses is to send a confirmation email with a link to click. This will only work if the email address is valid: easy, and no need to use regex.


    function check_email($check) {
    $expression = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+.([a-zA-Z]{2,4})$/";
    if (preg_match($expression, $check)) {
        return true;
    } else {
        return false;
    } 
    }
    

    在if()条件中调用它,如下例所示:

    if(!check_email($_REQUEST['ContactEmail'])){
      $register_error ="Enter the correct email address!<br />";
      $reg_error=1; 
    }
    
    链接地址: http://www.djcxy.com/p/16558.html

    上一篇: 正则表达式用于电子邮件验证

    下一篇: PHP电子邮件验证