如何检查字符串是否是有效的 XML 元素名称? [英] How to check if string is a valid XML element name?

查看:31
本文介绍了如何检查字符串是否是有效的 XML 元素名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 PHP 中的正则表达式或函数来验证字符串是否是一个好的 XML 元素名称.

I need a regex or a function in PHP that will validate a string to be a good XML element name.

表单 w3schools:

Form w3schools:

XML 元素必须遵循这些命名规则:

XML elements must follow these naming rules:

  1. 名称可以包含字母、数字和其他字符
  2. 名称不能以数字或标点符号开头
  3. 名称不能以字母 xml(或 XML、Xml 等)开头
  4. 名称不能包含空格

我可以编写一个基本的正则表达式来检查规则 1,2 和 4,但它不会考虑所有允许的标点符号,也不会考虑第三条规则

I can write a basic regex that will check for rules 1,2 and 4, but it won't account for all punctuation allowed and won't account for 3rd rule

w[w0-9-]

友好更新

这是格式良好的 XML 元素名称的更权威来源:

名称和标记

NameStartChar   ::=
    ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] |
    [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | 
    [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | 
    [#x10000-#xEFFFF]

NameChar    ::=
    NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]

Name    ::=
    NameStartChar (NameChar)*

还指定了单独的非标记化规则:

Also a separate non-tokenized rule is specified:

以字符串 "xml" 或任何匹配 (('X'|'x') ('M'|'m') ('L'|'l')) 开头的名称是保留用于本规范的本版本或未来版本的标准化.

Names beginning with the string "xml", or with any string which would match (('X'|'x') ('M'|'m') ('L'|'l')), are reserved for standardization in this or future versions of this specification.

推荐答案

怎么样

/A(?!XML)[a-z][w0-9-]*/i

用法:

if (preg_match('/A(?!XML)[a-z][w0-9-]*/i', $subject)) {
    # valid name
} else {
    # invalid name
}

说明:

A  Beginning of the string
(?!XML)  Negative lookahead (assert that it is impossible to match "XML")
[a-z]  Match a non-digit, non-punctuation character
[w0-9-]*  Match an arbitrary number of allowed characters
/i  make the whole thing case-insensitive

这篇关于如何检查字符串是否是有效的 XML 元素名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆