WordPress at Your Fingertips

sanitize_text_field() WP 2.9.0

Sanitizes the passed string leaving clean text: without HTML tags, line breaks, etc.

This function is used to sanitize strings before saving it to the database (passed from the input field), sometimes when received data (strings) from the database.

What exactly the function does:
  1. Checks for invalid UTF-8 encoding.
  2. Converts single < character to HTML entities.
  3. Strips all tags.
  4. Removes line breaks (\r\n), tabs (\t), and extra whitespace.
  5. Removes spaces at the beginning and end of the string.
  6. Replaces multiple spaces to single.
  7. Strips octets: %[a-f0-9]{2}.
What is the difference between esc_html() and sanitize_text_field():

esc_html() — it only translates HTML characters and entities into visible text, so that the browser does not process the text as HTML, i.e. it saves all data and makes it readable.

sanitize_text_field() — removes all HTML characters, line breaks, tabs, and HTML entities. The function leaves blank text, i.e. the function does everything to ensure that the value of the input field is safe to save.

Used By: wc_clean()
1 time — 0.000001 sec (speed of light) | 50000 times — 0.20 sec (very fast) | PHP 7.0.19, WP 5.0.2
Hooks from the function


String. Sanitized string.


sanitize_text_field( $str );
$str(string) (required)
String to sanitize.


#1 Demonstration of the function:

sanitize_text_field( 'Check <em>how</em>
the string is sanitized     <br>. ' );
//> 'Check how the string is sanitized.'

sanitize_text_field( 'http://example.com/foo.php#bar' );
//> 'http://example.com/foo.php#bar'

sanitize_text_field( 'foo <strong> bar' );
//> foo bar

sanitize_text_field( 123 );
//> string(3) "123"

sanitize_text_field( 'http://test.ru/%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82/' );
//> http://test.ru//

sanitize_text_field( '{ "Vlad Mir": "https://profiles.wordpress.org/sephp", "Kama": "https://wp-kama.com" }' );
//> { "Vlad Mir": "https://profiles.wordpress.org/sephp", "Kama": "https://wp-kama.com" }

#2 Using the function in input

This example shows how to use the function in the INPUT tag. Suppose we accept a $_POST request with a field value:

<input type="text" name="str" value="<?php echo esc_attr( sanitize_text_field( $_POST['str'] ) ) ?>" />



Since 2.9.0 Introduced.

Code of sanitize_text_field() WP 5.9

function sanitize_text_field( $str ) {
	$filtered = _sanitize_text_fields( $str, false );

	 * Filters a sanitized text field string.
	 * @since 2.9.0
	 * @param string $filtered The sanitized string.
	 * @param string $str      The string prior to being sanitized.
	return apply_filters( 'sanitize_text_field', $filtered, $str );


Sanitizing, Escaping

vladlu 100vlad.lu
Editors: Kama 101
No comments
    Log In