tag_escape()
云策文档标注
概述
tag_escape() 函数用于转义 HTML 标签名称,通过正则表达式清理和过滤,确保输出安全。它接受一个字符串参数,返回转义后的标签名,并可通过 'tag_escape' 过滤器进行自定义。
关键要点
- 函数接受一个必需的字符串参数 $tag_name,用于指定要转义的标签名
- 使用正则表达式 /[^a-zA-Z0-9-_:]/ 移除非法字符,并将结果转换为小写
- 返回转义后的字符串,并通过 apply_filters() 应用 'tag_escape' 过滤器,允许开发者修改输出
- 从 WordPress 2.5.0 版本引入,6.5.5 版本开始允许连字符(支持自定义元素)
代码示例
function tag_escape( $tag_name ) {
$safe_tag = strtolower( preg_replace( '/[^a-zA-Z0-9-_:]/', '', $tag_name ) );
/**
* Filters a string cleaned and escaped for output as an HTML tag.
*
* @since 2.8.0
*
* @param string $safe_tag The tag name after it has been escaped.
* @param string $tag_name The text before it was escaped.
*/
return apply_filters( 'tag_escape', $safe_tag, $tag_name );
}注意事项
- 函数主要用于安全输出 HTML 标签,避免 XSS 攻击等安全问题
- 相关函数包括 get_tag_regex() 和 gallery_shortcode(),用于标签匹配和短码处理
- 开发者可以通过 'tag_escape' 过滤器自定义转义逻辑,例如添加额外字符或修改清理规则
原文内容
Escapes an HTML tag name.
Parameters
$tag_namestringrequired
Source
function tag_escape( $tag_name ) {
$safe_tag = strtolower( preg_replace( '/[^a-zA-Z0-9-_:]/', '', $tag_name ) );
/**
* Filters a string cleaned and escaped for output as an HTML tag.
*
* @since 2.8.0
*
* @param string $safe_tag The tag name after it has been escaped.
* @param string $tag_name The text before it was escaped.
*/
return apply_filters( 'tag_escape', $safe_tag, $tag_name );
}
Hooks
- apply_filters( ‘tag_escape’, string $safe_tag, string $tag_name )
-
Filters a string cleaned and escaped for output as an HTML tag.