wp_kses_attr_parse()
云策文档标注
概述
wp_kses_attr_parse() 函数用于解析 HTML 元素中的所有属性,基于 wp_kses_split2() 和 wp_kses_attr() 实现,不修改输入但可能返回“恶意”输出。
关键要点
- 函数接受一个字符串参数 $element,表示 HTML 元素,返回属性数组或失败时返回 false。
- 使用正则表达式匹配元素结构,处理自闭合标签和 XHTML 斜杠,并调用 wp_kses_hair_parse() 解析属性。
- 在 WordPress 4.2.3 版本中引入,常用于 do_shortcodes_in_html_tags() 等函数中处理 HTML 元素内的短代码。
代码示例
function wp_kses_attr_parse( $element ) {
$valid = preg_match( '%^(]*)(>?)$%', $element, $matches );
if ( 1 !== $valid ) {
return false;
}
$begin = $matches[1];
$slash = $matches[2];
$elname = $matches[3];
$attr = $matches[4];
$end = $matches[5];
if ( '' !== $slash ) {
// Closing elements do not get parsed.
return false;
}
// Is there a closing XHTML slash at the end of the attributes?
if ( 1 === preg_match( '%s*/s*$%', $attr, $matches ) ) {
$xhtml_slash = $matches[0];
$attr = substr( $attr, 0, -strlen( $xhtml_slash ) );
} else {
$xhtml_slash = '';
}
// Split it.
$attrarr = wp_kses_hair_parse( $attr );
if ( false === $attrarr ) {
return false;
}
// Make sure all input is returned by adding front and back matter.
array_unshift( $attrarr, $begin . $slash . $elname );
array_push( $attrarr, $xhtml_slash . $end );
return $attrarr;
}
原文内容
Finds all attributes of an HTML element.
Description
Does not modify input. May return “evil” output.
Based on wp_kses_split2() and wp_kses_attr().
Parameters
$elementstringrequired-
HTML element.
Source
function wp_kses_attr_parse( $element ) {
$valid = preg_match( '%^(<s*)(/s*)?([a-zA-Z0-9]+s*)([^>]*)(>?)$%', $element, $matches );
if ( 1 !== $valid ) {
return false;
}
$begin = $matches[1];
$slash = $matches[2];
$elname = $matches[3];
$attr = $matches[4];
$end = $matches[5];
if ( '' !== $slash ) {
// Closing elements do not get parsed.
return false;
}
// Is there a closing XHTML slash at the end of the attributes?
if ( 1 === preg_match( '%s*/s*$%', $attr, $matches ) ) {
$xhtml_slash = $matches[0];
$attr = substr( $attr, 0, -strlen( $xhtml_slash ) );
} else {
$xhtml_slash = '';
}
// Split it.
$attrarr = wp_kses_hair_parse( $attr );
if ( false === $attrarr ) {
return false;
}
// Make sure all input is returned by adding front and back matter.
array_unshift( $attrarr, $begin . $slash . $elname );
array_push( $attrarr, $xhtml_slash . $end );
return $attrarr;
}
Changelog
| Version | Description |
|---|---|
| 4.2.3 | Introduced. |