Modify regex to validate email?

后端 未结 3 1650
感动是毒
感动是毒 2021-01-15 06:21

preg_match(\"/^[-\\w.]+@([A-z0-9][-A-z0-9]+\\.)+[A-z]{2,4}$/\", $email);

I want to modify this regex to allow emails such as user+one@wherever.com

3条回答
  •  猫巷女王i
    2021-01-15 07:06

    Just to point out a concern with the previous answers: '+' and '.' cannot be the first character in the username part of the email address. The correct regex should be

    preg_match("/^\w[-\w.+]*@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/", $email);
    

    Note that in order to validate against the full RFC 2822, you'll need something like this:

    preg_match('/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/', $email);
    

    However this is not very practical for most application. Have a look at this page for a detailed discussion of regex validation of email addresses.

提交回复
热议问题