get_tag_regex()
云策文档标注
概述
get_tag_regex() 函数用于生成一个正则表达式,以宽松匹配 HTML 开始标签。它支持自闭合标签、无内容但有闭合标签或包含内容且有闭合标签的情况,但不会平衡内部标签或确保 HTML 有效性。
关键要点
- 函数返回一个正则表达式字符串,用于匹配 HTML 开始标签。
- 参数 $tag 是必需的,指定 HTML 标签名(如 'video')。
- 正则表达式不处理标签内部平衡,也不保证生成有效的 HTML。
- 相关函数包括 tag_escape(),用于转义 HTML 标签名。
代码示例
function get_tag_regex( $tag ) {
if ( empty( $tag ) ) {
return '';
}
return sprintf( '<%s(?:[^>]*?(?!/>)|s*/>)', tag_escape( $tag ) );
}注意事项
- 此正则表达式设计为宽松匹配,可能不适用于需要严格 HTML 验证的场景。
- 从 WordPress 3.6.0 版本开始引入。
原文内容
Returns RegEx body to liberally match an opening HTML tag.
Description
Matches an opening HTML tag that:
- Is self-closing or
- Has no body but has a closing tag of the same name or
- Contains a body and a closing tag of the same name
Note: this RegEx does not balance inner tags and does not attempt to produce valid HTML
Parameters
$tagstringrequired-
An HTML tag name. Example:
'video'.
Source
function get_tag_regex( $tag ) {
if ( empty( $tag ) ) {
return '';
}
return sprintf( '<%1$s[^<]*(?:>[sS]*</%1$s>|s*/>)', tag_escape( $tag ) );
}
Changelog
| Version | Description |
|---|---|
| 3.6.0 | Introduced. |