使用正则表达式进行简单的电子邮件验证
在我的注册表单上,用户将添加他的电子邮件,然后收到一封电子邮件来验证他的帐户。不过,我想要进行简单的电子邮件验证,并且我想知道以下内容是否合适。
<?php
$email = "[email protected]";
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
echo "Valid email address.";
}
else {
echo "Invalid email address.";
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
Try:
您的正则表达式不必要地禁止子域,例如
[email protected]
。此外,您不应使用已弃用的eregi
。不要重新发明自己的轮子,而是使用
filter_var
:Your regular expression unnecessarily forbids subdomains, such as
[email protected]
. Additionally, you shouldn't use the deprecatederegi
.Instead of reinventing your own wheel, use
filter_var
:除了正则表达式之外,您还可以使用
filter_var
:Apart from a regex, you can also use
filter_var
:电子邮件验证有点棘手,因为 RFC 指定了电子邮件的格式地址比人们想象的更不受限制。例如,以下都是有效的电子邮件地址:
电子邮件验证的正确正则表达式似乎类似于 这个,我什至不会尝试研究它;)但是,在使用 PHP 时,您确实应该使用 filter_var(),如下所示:
RFC822 似乎包含原始电子邮件格式规范,但我认为 2822(如上面链接的)只是原始 RFC 的修订/修正。
Email validation is a bit tricky, because the RFC that specifies the format of email addresses is way more unrestrictive that people think. For example, the following are all valid email addresses:
The correct regex for email validation seems to look something like this, which I won't even try to look into ;) However, when using PHP, you should really use filter_var(), like so:
RFC822 seems to contain the original email format specification, but I think that 2822 (as linked above) is just a revision / amendment of that original RFC.