sanitize_html_class

Sanitizes an HTML classname to ensure it only contains valid characters.

Description

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

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.

Returns (string)

The sanitized value

Parameters (2)

0. $class (string)
The classname to be sanitized
1. $fallback — Optional. (string) => ''
The value to return if the sanitization ends up as an empty string. Defaults to an empty string.

Usage

  1. if ( !function_exists( 'sanitize_html_class' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // The classname to be sanitized 
  5. $class = ''; 
  6.  
  7. // Optional. The value to return if the sanitization ends up as an empty string. 
  8. // Defaults to an empty string. 
  9. $fallback = ''; 
  10.  
  11. // NOTICE! Understand what this does before running. 
  12. $result = sanitize_html_class($class, $fallback); 
  13.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function sanitize_html_class( $class, $fallback = '' ) { 
  2. //Strip out any % encoded octets 
  3. $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class ); 
  4.  
  5. //Limit to A-Z, a-z, 0-9, _, - 
  6. $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized ); 
  7.  
  8. if ( '' == $sanitized && $fallback ) { 
  9. return sanitize_html_class( $fallback ); 
  10. /** 
  11. * Filters a sanitized HTML class string. 
  12. * @since 2.8.0 
  13. * @param string $sanitized The sanitized HTML class. 
  14. * @param string $class HTML class before sanitization. 
  15. * @param string $fallback The fallback string. 
  16. */ 
  17. return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );