2011-04-02 17 views
1

如HTML 4規範說明的是:使用PHP在HTML中驗證ID /名稱令牌?

ID和名稱標記必須以字母開頭([A-ZA-Z])和之後可以是任何數量的字母,數字([0-9 ]),連字符(「 - 」),下劃線(「_」),冒號(「:」)和句點(「。」)。

如何使用PHP驗證ID/NAME標記是否有效?

回答

3

我想一個正規表達式,比如這個人可以做的伎倆:

^[A-Za-z][A-Za-z0-9_:\.-]* 

有關詳細信息,請參閱本手冊的以下部分:Regular Expressions (Perl-Compatible)


並使用,在PHP,你必須使用preg_match()函數:

if (preg_match('/^[A-Za-z][A-Za-z0-9_:\.-]*/', $id)) { 
    // valid 
} 
+0

哼,沒有也不會 - 閱讀問題得太快,我想:-(感謝您的評論,我我修改了我的答案以修復該問題 – 2011-04-02 15:47:57

2

Regular Exp ressions。 /^[a-z]+[\w\_\-\:\.]*/i

說明:

/    #beginning of regular-expression 
[a-z]   #match any lowercase English letter 
+    #match previous token one or more times 
[\w\_\-\:\.] #match any word or digit, underscore, hyphen, colon or dot 
*    #match previous token zero or more times 
/i   #end regular expression with the i modifier, making it case-insensitive 

用PHP,您可以使用preg_match得到驗證。

有關正則表達式的詳細信息,請regular-expressions.infoGSkinner的正則表達式測試

+0

i修飾符使表達式不區分大小寫 – Zirak 2011-04-02 15:34:36

+0

這兩個答案都非常有用,非常感謝您。 – Teiv 2011-04-02 15:54:46