sanitize_html_class()WP 2.8.0

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.

1 time — 0.000024 sec (very fast) | 50000 times — 0.08 sec (speed of light) | PHP 7.1.2, WP 4.7.3
Hooks from the function

Return

String. The sanitized value.

Usage

sanitize_html_class( $classname, $fallback );
$classname(string) (required)
The classname to be sanitized.
$fallback(string)
The value to return if the sanitization ends up as an empty string.
Default: empty string

Examples

0

#1 Demo

$text = 'Δοκιμαστικό κείμενο';
echo sanitize_html_class( $text ); // '' (empty string)

$text = 'Some text';
echo sanitize_html_class( $text ); // Sometext

$text = 'foo bar';
echo sanitize_html_class( $text ); // foobar

$text = 'my-class';
echo sanitize_html_class( $text ); // my-class

$text = 'Δοκι κείμενο - Example';
echo sanitize_html_class( $text ); // -Example

But: Class names must not start with numbers and this function does not take this into account. This function return a string starting with digits which by W3 definition are not valid class names.

$text = '2foo';
echo  sanitize_html_class( $text ); // 2foo
0

#2 Escape multiple HTML classes

Bellow the function that accepts 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( $classes ){
			foreach( $classes as $class ){
				$return .= sanitize_html_class( $class ) . ' ';
			}
		}

		return $return;
	}

}

Changelog

Since 2.8.0 Introduced.

sanitize_html_class() code WP 6.4.3

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 );
}