php preg_match 与电子邮件验证问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13447539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php preg_match with email validation issue
提问by Om3ga
I am validating email address using php with preg_matchfunction. But I keep getting following error
我正在使用带有preg_match函数的php 验证电子邮件地址。但我不断收到以下错误
preg_match(): No ending delimiter '^' found
here is my pattern for preg_match
这是我的 preg_match 模式
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
How to fix this?
如何解决这个问题?
回答by Shoe
Just use:
只需使用:
$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i";
回答by André Keller
Maybe using
也许使用
filter_var($email, FILTER_VALIDATE_EMAIL);
Would be an easier approach.
将是一个更简单的方法。
回答by manish1706
use this code
使用此代码
<?php
$email = "asd/[email protected]";
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
$email = (preg_match($regex, $email))?$email:"invalid email";
?>
回答by Pinonirvana
Because of the issues caused by FILTER_VALIDATE_EMAIL (for instance it doesn't work well with not-latin characters), I prefer to use:
由于 FILTER_VALIDATE_EMAIL 引起的问题(例如它不适用于非拉丁字符),我更喜欢使用:
preg_match("/^[^@]+@[^@]+\.[a-z]{2,6}$/i",$email_address);
preg_match("/^[^@]+@[^@]+\.[a-z]{2,6}$/i",$email_address);
回答by muskose
This is a simple email validation method with regex:
这是一个使用正则表达式的简单电子邮件验证方法:
public function emailValidation($email)
{
$regex = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,10})$/";
$email = strtolower($email);
return preg_match ($regex, $email);
}
回答by Anthony Rutledge
Using the function filter_var() in PHP would only be easier if a postmaster wanted to allow an RFC style match for e-mail addresses. For some applications or MTAs (sendmail, etc...), this might not be desirable. However, if one is to go the preg_match() route, I would suggest investigating non-greedy quantifiers and capture statements that do not use buffers. A good place to start would be http://us3.php.net/manual/en/book.pcre.php.
如果邮局管理员希望允许电子邮件地址的 RFC 样式匹配,那么在 PHP 中使用 filter_var() 函数会更容易。对于某些应用程序或 MTA(sendmail 等),这可能是不可取的。但是,如果要走 preg_match() 路线,我建议研究非贪婪量词并捕获不使用缓冲区的语句。一个好的起点是http://us3.php.net/manual/en/book.pcre.php。
回答by rOcKiNg RhO
var emailid = $.trim($('#emailid').val());
if( ! /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailid)){
alert("<?php echo "email_invalid" ?>");
return false;
}

