sanitize_html_class() WordPress Function

The sanitize_html_class() function is used to sanitize a string for use as a valid HTML class name. This function is useful when creating dynamic CSS classes, or when allowing user-inputted class names.

sanitize_html_class( string $class, string $fallback = '' ) #

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.


Top ↑

Parameters

$class

(string)(Required)The classname to be sanitized

$fallback

(string)(Optional) The value to return if the sanitization ends up as an empty string. Defaults to an empty string.

Default value: ''


Top ↑

Return

(string) The sanitized value


Top ↑

Source

File: wp-includes/formatting.php

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 && $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 $class     HTML class before sanitization.
	 * @param string $fallback  The fallback string.
	 */
	return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
}


Top ↑

Changelog

Changelog
VersionDescription
2.8.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More