1. 首页
  2. WordPress 函数手册

sanitize_html_class()

sanitize_html_class( string $class, string $fallback =  )

清理HTML类名以确保它只包含有效字符。
Sanitizes an HTML classname to ensure it only contains valid characters.

目录锚点:#说明#参数#返回#源码#笔记


说明(Description)

把绳子拉到A-Z,A-Z,0-9,,-。如果这导致一个空字符串,那么它将返回提供的替代值。


参数(Parameters)

参数 类型 必填 说明
$class (string) 必需 要消毒的类名
$fallback (string) 可选 如果清理结束为空字符串,则返回的值。默认为空字符串。

返回(Return)

(string)消毒值


源码(Source)

/**
 * Sanitizes an HTML classname to ensure it only contains valid characters.
 *
 * 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.
 *
 * @todo Expand to support the full range of CDATA that a class attribute can contain.
 *
 * @since 2.8.0
 *
 * @param string $class    The classname to be sanitized
 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
 * 	Defaults to an empty string.
 * @return string The sanitized value
 */
function sanitize_html_class( $class, $fallback = '' ) {
	//Strip out any % encoded octets
	$sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );

	//Limit to A-Z,a-z,0-9,_,-
	$sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );

	if ( '' == $sanitized )
		$sanitized = $fallback;

	/**
	 * Filter a sanitized HTML class string.
	 *
	 * @since 2.8.0
	 *
	 * @param string $sanitized The sanitized HTML class.
	 * @param string $class     HTML class before sanitization.
	 * @param string $fallback  The fallback string.
	 */
	return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
}
更新版本 源码位置 使用 被使用
2.8.0 wp-includes/formatting.php:2333 15 3

笔记(Notes)

创建此函数是为了帮助转义多个HTML类,您可以给它一个类数组或一个用分隔符分隔的类字符串:
基本示例
类名不能以数字开头,并且此函数不将其作为计数。

sanitize_html_class() 为WP2原创文章,链接:https://www.wp2.cn/functions/sanitize_html_class/

发表评论

您的电子邮箱地址不会被公开。