2015-02-08 100 views
0

我正在關注一本書來學習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'; } 

有人能向我解釋什麼「$模式」是幹什麼的? 我不確定,但從我以前知道的關於連接到網站的應用程序的編碼中,我認爲它可能是所謂的「正則表達式」?

如果有人能向我解釋這一行,我很感激。另外,如果它是「正則表達式」,你能提供一個鏈接到某個地方,只是簡單地解釋它是什麼以及它是如何工作的?

+0

對於這種特定情況:[如何驗證PHP中的電子郵件地址](http://stackoverflow.com/q/12026842) – mario 2015-02-08 21:36:19

回答

1

正則表達式是一個正則表達式:它是描述一組字符串的模式,通常是所有可能字符串集合的一個子集。正則表達式可以使用的所有特殊字符在問題中已被解釋,您的問題已被標記爲重複。

但專門爲你的情況;有一個很好的工具,它可以解釋的正則表達式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 
} 

您不必擔心邊界情況或任何東西。

相關問題