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.
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: ''
Return
(string) The sanitized value
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 ); }
Expand full source code Collapse full source code View on Trac View on GitHub
Changelog
Version | Description |
---|---|
2.8.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
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.
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:
Expand full source codeCollapse full source code
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.Expand full source codeCollapse full source code