【问题标题】:Validate a ID/NAME tokens in HTML using PHP?使用 PHP 在 HTML 中验证 ID/NAME 令牌?
【发布时间】:2011-04-02 15:11:58
【问题描述】:

正如在 HTML 4 规范中指出的那样:

ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 (" _")、冒号 (":") 和句点 (".")。

如何使用 PHP 验证 ID/NAME 令牌是否有效?

【问题讨论】:

    标签: php validation token


    【解决方案1】:

    我想像这样的正则表达式可以解决问题:

    ^[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
    }
    

    【讨论】:

    • 哼,不会——我想这个问题读得太快了:-(感谢您的评论,我已经编辑了我的答案来解决这个问题
    【解决方案2】:

    正则表达式。 /^[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 的正则表达式测试

    【讨论】:

    • i 修饰符使表达式不区分大小写
    • 这两个答案都非常有帮助。非常感谢大家。
    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 2017-06-25
    • 2019-06-28
    • 1970-01-01
    • 2021-04-08
    • 2016-12-27
    • 2017-01-24
    • 2020-07-25
    相关资源
    最近更新 更多