_sanitize_text_fields

Internal helper function to sanitize a string from user input or from the db.

Description

(string) _sanitize_text_fields( (string) $str, (bool) $keep_newlines = false ); 

Returns (string)

Sanitized string.

Parameters (2)

0. $str (string)
String to sanitize.
1. $keep_newlines — Optional. (bool) => false
Whether to keep newlines. Default: false.

Usage

  1. if ( !function_exists( '_sanitize_text_fields' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // String to sanitize. 
  5. $str = ''; 
  6.  
  7. // optional Whether to keep newlines. Default: false. 
  8. $keep_newlines = false; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = _sanitize_text_fields($str, $keep_newlines); 
  12.  

Defined (1)

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

/wp-includes/formatting.php  
  1. function _sanitize_text_fields( $str, $keep_newlines = false ) { 
  2. $filtered = wp_check_invalid_utf8( $str ); 
  3.  
  4. if ( strpos($filtered, '<') !== false ) { 
  5. $filtered = wp_pre_kses_less_than( $filtered ); 
  6. // This will strip extra whitespace for us. 
  7. $filtered = wp_strip_all_tags( $filtered, false ); 
  8.  
  9. // Use html entities in a special case to make sure no later 
  10. // newline stripping stage could lead to a functional tag 
  11. $filtered = str_replace("<\n", "<\n", $filtered); 
  12.  
  13. if ( ! $keep_newlines ) { 
  14. $filtered = preg_replace( '/[\r\n\t ]+/', ' ', $filtered ); 
  15. $filtered = trim( $filtered ); 
  16.  
  17. $found = false; 
  18. while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) { 
  19. $filtered = str_replace($match[0], '', $filtered); 
  20. $found = true; 
  21.  
  22. if ( $found ) { 
  23. // Strip out the whitespace that may now exist after removing the octets. 
  24. $filtered = trim( preg_replace('/ +/', ' ', $filtered) ); 
  25.  
  26. return $filtered;