sanitize_html_class()WP 2.8.0

Prepares text for use in the HTML class attribute: removes all unsuitable characters.

The function removes all octets and all characters not included in the set: A-Z, a-z, 0-9, _, -.
If the result is an empty string, the function will return the alternative class specified in the second parameter $fallback.

Before returning the data the result is passed through the sanitize_html_class filter.

Note that the function handles only a single class. I.e., if you pass 2 classes at once like: foo bar, the space will be removed and you will get: foobar.

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

Returns

String.

Usage

$sanitized = sanitize_html_class( $class, $fallback );
$class(string) (required)
The string (class name) to sanitize.
$fallback(string)
The value to return if the original value becomes an empty string after sanitization.
Default: ''

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:

function sanitize_html_classes( string|array $classes ): string {
	if( ! is_array( $classes ) ){
		$classes = explode( ' ', $classes );
	}

	$sanitized = '';

	foreach( $classes as $class ){
		$sanitized .= sanitize_html_class( $class ) . ' ';
	}

	return $sanitized;
}

Changelog

Since 2.8.0 Introduced.

sanitize_html_class() code WP 6.9.1

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