sanitize_text_field( string $str )

Sanitizes a string from user input or from the database.


Description #

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

Parameters #

$str

(string) (Required)


Top ↑

Return #

(string)


Top ↑

Source #

File: wp-includes/formatting.php

function sanitize_text_field( $str ) {
	$filtered = wp_check_invalid_utf8( $str );

	if ( strpos($filtered, '<') !== false ) {
		$filtered = wp_pre_kses_less_than( $filtered );
		// This will strip extra whitespace for us.
		$filtered = wp_strip_all_tags( $filtered, true );
	} else {
		$filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
	}

	$found = false;
	while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
		$filtered = str_replace($match[0], '', $filtered);
		$found = true;
	}

	if ( $found ) {
		// Strip out the whitespace that may now exist after removing the octets.
		$filtered = trim( preg_replace('/ +/', ' ', $filtered) );
	}

	/**
	 * Filter 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 );
}


Top ↑

Changelog #

Changelog
Version Description
2.9.0 Introduced.

Top ↑

More Information #

Basic Usage

<?php sanitize_text_field( $str ) ?>


Top ↑

User Contributed Notes #

You must log in before being able to contribute a note.