sanitize_text_field

Sanitizes a string from user input or from the database.

Description

(string) sanitize_text_field( (string) $str ); 

- Checks for invalid UTF-8, - Converts single < characters to entities - Strips all tags - Removes line breaks, tabs, and extra whitespace - Strips octets

Returns (string)

Sanitized string.

Parameters (1)

0. $str (string)
String to sanitize.

Usage

  1. if ( !function_exists( 'sanitize_text_field' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // String to sanitize. 
  5. $str = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = sanitize_text_field($str); 
  9.  

Defined (1)

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

/wp-includes/formatting.php  
  1. function sanitize_text_field( $str ) { 
  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, true ); 
  8. } else { 
  9. $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) ); 
  10.  
  11. $found = false; 
  12. while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) { 
  13. $filtered = str_replace($match[0], '', $filtered); 
  14. $found = true; 
  15.  
  16. if ( $found ) { 
  17. // Strip out the whitespace that may now exist after removing the octets. 
  18. $filtered = trim( preg_replace('/ +/', ' ', $filtered) ); 
  19.  
  20. /** 
  21. * Filters a sanitized text field string. 
  22. * @since 2.9.0 
  23. * @param string $filtered The sanitized string. 
  24. * @param string $str The string prior to being sanitized. 
  25. */ 
  26. return apply_filters( 'sanitize_text_field', $filtered, $str );