sanitize_html_class()清理 HTML Class 名,保证只包含合法的字符

目录

描述

 理 HTML Class 名,保证 包含合  符。

  非法的字 只剩下 A-Z,a-z,0-9,_,-,    空字 串,那 这个函数将返回替代的值。

在 sanitize_html_class() 完成工作的时候,会执行 sanitize_html_class 过滤器。

sanitize_html_class() 描述

参数

$class

(string) (必填) 要清理的 classname。

默认值: None

$fallback

(string) (可选) 替代 ,如果 理的结果是 字符  ,使用这个这个值代替。

 值: None

sanitize_html_class() 参数

返回值

string (string

 理之后的值

sanitize_html_class() 返回值

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
// 如果你想给一篇日志一个独特的风格,可以使用经过这个函数处理的日志标题作为 class
$post_class = sanitize_html_class( $post->post_title );
echo '<div class="' . $post_class . '">';
?>

sanitize_html_class() 示例

历史

  • 添加于 版本: 2.8.0

sanitize_html_class() 历史

源文件

sanitize_html_class() 函数的代码位于 wp-includes/formatting.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * 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 );
}

sanitize_html_class() 源文件

相关