如何在PHP中验证电子邮件? [英] How to validate an Email in PHP?
问题描述
如何使用php5验证输入值是有效的电子邮件地址.现在,我正在使用此代码
How can I validate the input value is a valid email address using php5. Now I am using this code
function isValidEmail($email){
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (eregi($pattern, $email)){
return true;
}
else {
return false;
}
}
,但显示不赞成使用的错误.我该如何解决此问题.请帮助我.
but it shows deprecated error. How can I fix this issue. Please help me.
推荐答案
您可以使用filter_var()
函数,该函数为您提供了许多方便的验证和消毒选项.
You can use the filter_var()
function, which gives you a lot of handy validation and sanitization options.
filter_var($email, FILTER_VALIDATE_EMAIL)
-
在 PHP> = 5.2.0
如果您不想更改依赖于功能的代码,只需执行以下操作:
If you don't want to change your code that relied on your function, just do:
function isValidEmail($email){ return filter_var($email, FILTER_VALIDATE_EMAIL) !== false; }
注意:对于其他用途(需要Regex的情况),应使用
preg
系列(Note: For other uses (where you need Regex), the deprecated
ereg
function family (POSIX Regex Functions) should be replaced by thepreg
family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.更新1 :由
PHP 5.3.3和5.2.14的 bug 与 FILTER_VALIDATE_EMAIL,这在验证时导致段错误 大价值.为此,简单安全的解决方法是使用
strlen()
在filter_var()
之前.我不确定5.3.4最终版本,但这是 写道,一些5.3.4快照版本也受到了影响.PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using
strlen()
beforefilter_var()
. I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.此错误已得到修复.
更新2 :该方法当然会将
bazmega@kapa
验证为有效的电子邮件地址,因为实际上它是有效的电子邮件地址.但是大多数时候,在Internet上,您还希望电子邮件地址具有TLD:bazmega@kapa.com
.如本博客文章(由 @Istiaque Ahmed ),您可以使用一个将检查域部分中是否存在点的正则表达式(尽管不会检查 valid TLD):Update 2: This method will of course validate
bazmega@kapa
as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD:bazmega@kapa.com
. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augmentfilter_var()
with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):function isValidEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email); }
@Eliseo Ocampos 指出,此问题仅在PHP 5.3之前存在,
As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.
这篇关于如何在PHP中验证电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!