使用...正则表达式验证PHP中的电子邮件?
问题描述:
我正在关注一本书来学习PHP,我有一个问题!使用...正则表达式验证PHP中的电子邮件?
这是电子邮件验证代码的一部分:
$pattern = '/\b[\w.-][email protected][\w.-]+\.[A-Za-z]{2,6}\b/';
if(!preg_match($pattern, $email))
{ $email = NULL; echo 'Email address is incorrect format'; }
有人能向我解释什么“$模式”是干什么的? 我不确定,但从我以前知道的关于连接到网站的应用程序的编码中,我认为它可能是所谓的“正则表达式”?
如果有人能向我解释这一行,我很感激。另外,如果它是“正则表达式”,你能提供一个链接到某个地方,只是简单地解释它是什么以及它是如何工作的?
答
正则表达式是一个正则表达式:它是描述一组字符串的模式,通常是所有可能字符串集合的一个子集。正则表达式可以使用的所有特殊字符在问题中已被解释,您的问题已被标记为重复。
但专门为你的情况;有一个很好的工具,它可以解释的正则表达式here:
NODE EXPLANATION
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
[\w.-]+ any character of: word characters (a-z, A-
Z, 0-9, _), '.', '-' (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
@ '@'
--------------------------------------------------------------------------------
[\w.-]+ any character of: word characters (a-z, A-
Z, 0-9, _), '.', '-' (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
[A-Za-z]{2,6} any character of: 'A' to 'Z', 'a' to 'z'
(between 2 and 6 times (matching the most
amount possible))
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
验证电子邮件地址,
但是,如果你正在使用PHP> = 5.2.0(这你可能是),你不正确的方式为此需要使用正则表达式。这是更清晰的代码使用内置filter_var():
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// email valid
} else {
// email invalid
}
您不必担心边界情况或任何东西。
对于这种特定情况:[如何验证PHP中的电子邮件地址](http://*.com/q/12026842) – mario 2015-02-08 21:36:19