sanitize_user

Sanitizes a username, stripping out unsafe characters.

Description

(string) sanitize_user( (string) $username, (bool) $strict = false ); 

Removes tags, octets, entities, and if strict is enabled, will only keep alphanumeric, _, space, ., -, @. After sanitizing, it passes the username, raw username (the username in the parameter), and the value of $strict as parameters for the filter.

Returns (string)

The sanitized username, after passing through filters.

Parameters (2)

0. $username (string)
The username to be sanitized.
1. $strict — Optional. (bool) => false
If set limits $username to specific characters. Default false.

Usage

  1. if ( !function_exists( 'sanitize_user' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // The username to be sanitized. 
  5. $username = ''; 
  6.  
  7. // If set limits $username to specific characters. Default false. 
  8. $strict = false; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = sanitize_user($username, $strict); 
  12.  

Defined (1)

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

/wp-includes/formatting.php  
  1. function sanitize_user( $username, $strict = false ) { 
  2. $raw_username = $username; 
  3. $username = wp_strip_all_tags( $username ); 
  4. $username = remove_accents( $username ); 
  5. // Kill octets 
  6. $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username ); 
  7. $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities 
  8.  
  9. // If strict, reduce to ASCII for max portability. 
  10. if ( $strict ) 
  11. $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username ); 
  12.  
  13. $username = trim( $username ); 
  14. // Consolidate contiguous whitespace 
  15. $username = preg_replace( '|\s+|', ' ', $username ); 
  16.  
  17. /** 
  18. * Filters a sanitized username string. 
  19. * @since 2.0.1 
  20. * @param string $username Sanitized username. 
  21. * @param string $raw_username The username prior to sanitization. 
  22. * @param bool $strict Whether to limit the sanitization to specific characters. Default false. 
  23. */ 
  24. return apply_filters( 'sanitize_user', $username, $raw_username, $strict );