使用PHP验证HTML中的ID / NAME令牌?

As in HTML 4 specification noted that :

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

How can I validate an ID/NAME token is valid by using PHP?

I suppose a regular expression such as this one could do the trick :

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

For more informations, see the following section of the manual : Regular Expressions (Perl-Compatible)


And to use that, in PHP, you'd have to use the preg_match() function :

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

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

Explanation:

/             #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

With php you can use preg_match to get validation.

For more info on regular expressions, check out regular-expressions.info and GSkinner's regexp test