sanitize_html_class()
云策文档标注
概述
sanitize_html_class() 函数用于清理 HTML 类名,确保其仅包含有效字符。它通过正则表达式移除无效字符,并支持备用值处理空结果。
关键要点
- 函数作用:清理 HTML 类名字符串,仅保留 A-Z、a-z、0-9、_ 和 - 字符。
- 参数说明:$classname(必需,待清理的类名),$fallback(可选,清理后为空字符串时的备用值,默认为空字符串)。
- 返回值:返回清理后的字符串,若清理结果为空且提供了 $fallback,则递归清理备用值。
- Hook 支持:通过 apply_filters('sanitize_html_class', $sanitized, $classname, $fallback) 允许过滤清理后的类名。
- 注意事项:函数不检查类名是否以数字开头(根据 W3C 规范可能无效),开发者需自行处理或使用提供的过滤器示例。
代码示例
// 基本用法示例
$class = sanitize_html_class( 'my-class_123', 'default-class' );
echo '<div class="' . esc_attr( $class ) . '">Content</div>';
// 使用过滤器处理以数字开头的类名
add_filter(
'sanitize_html_class',
function( string $sanitized, string $original, string $fallback ): string {
return preg_replace('#^(-([0-9]+|$)|[0-9]+)#', '', $sanitized) ?: $fallback;
},
10,
3
);
原文内容
Sanitizes an HTML classname to ensure it only contains valid characters.
Description
Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty string then it will return the alternative value supplied.
Parameters
$classnamestringrequired-
The classname to be sanitized.
$fallbackstringoptional-
The value to return if the sanitization ends up as an empty string.
Default empty string.
Source
function sanitize_html_class( $classname, $fallback = '' ) {
// Strip out any percent-encoded characters.
$sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $classname );
// Limit to A-Z, a-z, 0-9, '_', '-'.
$sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
if ( '' === $sanitized && $fallback ) {
return sanitize_html_class( $fallback );
}
/**
* Filters a sanitized HTML class string.
*
* @since 2.8.0
*
* @param string $sanitized The sanitized HTML class.
* @param string $classname HTML class before sanitization.
* @param string $fallback The fallback string.
*/
return apply_filters( 'sanitize_html_class', $sanitized, $classname, $fallback );
}
Hooks
- apply_filters( ‘sanitize_html_class’, string $sanitized, string $classname, string $fallback )
-
Filters a sanitized HTML class string.
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Skip to note 6 content
elnico
Class names must not start with numbers and this function does not take this into acount.
https://www.w3.org/TR/CSS21/syndata.html#characters
This function may return a string starting with digits which by W3 definition are not valid class names.
add_filter( 'sanitize_html_class', function( string $sanitized, string $original, string $fallback, ): string { return preg_replace('#^(-([0-9]+|$)|[0-9]+)#', '', $sanitized) ?: $fallback; }, 10, 3, );Skip to note 7 content
lieutenantdan
Created this function to help escape multiple HTML classes, you can give it an array of classes or a string of them separated by a delimiter:
if( ! function_exists("sanitize_html_classes") ){ function sanitize_html_classes($classes, $sep = " "){ $return = ""; if(!is_array($classes)) { $classes = explode($sep, $classes); } if(!empty($classes)){ foreach($classes as $class){ $return .= sanitize_html_class($class) . " "; } } return $return; } }Skip to note 8 content
Codex
Basic Example
post_title ); echo '<div class="' . $post_class . '">'; ?>Skip to note 9 content
Mahdi Yazdani
Sanitize multiple HTML classes in one pass.
Accepts either an array of
$classes, or a space-separated string of class names and runs them to sanitize using thesanitize_html_classfunction./** * Sanitize multiple HTML classes in one pass. * * @param array $classes Classes to be sanitized. * @param string $return_format The return format, 'input', 'string', or 'array'. * @return array|string */ function prefix_sanitize_html_classes( $classes, $return_format = 'input' ) { if ( 'input' === $return_format ) { $return_format = is_array( $classes ) ? 'array' : 'string'; } $classes = is_array( $classes ) ? $classes : explode( ' ', $classes ); $sanitized_classes = array_map( 'sanitize_html_class', $classes ); if ( 'array' === $return_format ) { return $sanitized_classes; } else { return implode( ' ', $sanitized_classes ); } }Skip to note 10 content
wbeaumo
As was previously mentioned, this function does not take into account that class names may not start with numbers. Class names MAY start with a dash (-) but ONLY if it is followed by a non-numeric character (so, dash followed by numbers or by itself is invalid). I wrote this filter to do additional checks on class names:
<br />
add_filter(<br />
'sanitize_html_class',<br />
function(<br />
string $sanitized,<br />
string $original,<br />
string $fallback,<br />
): string {<br />
return preg_replace('#^(-([0-9]+|$)|[0-9]+)#', '', $sanitized) ?: $fallback;<br />
},<br />
10,<br />
3,<br />
);<br />
(Apologies for the repeat comment, I did not realize that responding to someone else’s message would mean my response doesn’t show by default, nor did I realize that it would mangle my code’s whitespace. I don’t know how to delete my earlier comment.)