使用..在PHP中验证电子邮件..正则表达式


Validate email in PHP using... regex?

我正在关注一本学习PHP的书,我有一个问题!

这是电子邮件验证代码的一部分:

$pattern = '/'b['w.-]+@['w.-]+'.[A-Za-z]{2,6}'b/';
if(!preg_match($pattern, $email))
{ $email = NULL; echo 'Email address is incorrect format'; }

有人能向我解释一下"$pattern"在做什么吗?我不确定,但根据我之前对连接到网站的应用程序编码的了解,我认为它可能是一种叫做"Regex"的东西?

如果有人能向我解释这句话,我很感激。如果是"Regex",你能提供一个链接到某个地方,简要解释它是什么以及它是如何工作的吗?

正则表达式是一个正则表达式:它是一种描述字符串集的模式,通常是所有可能字符串集的子集。正则表达式可以使用的所有特殊字符都会在您的问题被标记为重复的问题中进行解释。

但具体针对您的情况;这里有一个很好的工具可以解释正则表达式:

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.20(可能是这样),则不需要使用正则表达式。使用内置的filter_var():的代码要清晰得多

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // email valid
} else {
    // email invalid
}

你不必担心边界情况或任何事情。