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.
Parameters
$classname
stringrequired- The classname to be sanitized.
$fallback
stringoptional- The value to return if the sanitization ends up as an empty string.
Default:
''
Source
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 );
}
Hooks
- apply_filters( ‘sanitize_html_class’,
string $sanitized ,string $classname ,string $fallback ) Filters a sanitized HTML class string.
Changelog
Version | Description |
---|---|
2.8.0 | Introduced. |
Class names must not start with numbers and this function does not take this into acount.
https://www.w3.org/TR/CSS21/syndata.html#characters
This function may return a string starting with digits which by W3 definition are not valid class names.
add_filter( 'sanitize_html_class', function( string $sanitized, string $original, string $fallback, ): string { return preg_replace('#^(-([0-9]+|$)|[0-9]+)#', '', $sanitized) ?: $fallback; }, 10, 3, );
Created this function to help escape multiple HTML classes, you can give it an array of classes or a string of them separated by a delimiter:
Basic Example
Sanitize multiple HTML classes in one pass.
Accepts either an array of
$classes
, or a space-separated string of class names and runs them to sanitize using thesanitize_html_class
function.As was previously mentioned, this function does not take into account that class names may not start with numbers. Class names MAY start with a dash (-) but ONLY if it is followed by a non-numeric character (so, dash followed by numbers or by itself is invalid). I wrote this filter to do additional checks on class names:
add_filter(
'sanitize_html_class',
function(
string $sanitized,
string $original,
string $fallback,
): string {
return preg_replace('#^(-([0-9]+|$)|[0-9]+)#', '', $sanitized) ?: $fallback;
},
10,
3,
);
(Apologies for the repeat comment, I did not realize that responding to someone else’s message would mean my response doesn’t show by default, nor did I realize that it would mangle my code’s whitespace. I don’t know how to delete my earlier comment.)