wppaste
WordPress

sanitize_text_field( string $str ): string

Since
2.9.0
Source
wp-includes/formatting.php:5574

Strips tags, invalid UTF-8, line breaks, extra whitespace and percent-encoded characters from a single-line string, returning the cleaned result. Built for short user-supplied fields like a name or subject line rather than multi-line content. It runs through the sanitize_text_field filter before returning, so plugins can alter the result. For fields where line breaks matter, use sanitize_textarea_field instead.

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 percent-encoded characters

Compatibility

WordPress
since 2.9.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$strstring
String to sanitize.

Return value

string
Sanitized string.

Code examples

Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.

Sanitize a text field submitted via $_POST before saving it

A form handler receives a raw customer name with extra whitespace and a stray tag that needs to be stripped before it touches post meta.

$_POST['customer_name'] = "  Jane <b>Doe</b>\n\t ";

$clean_name = sanitize_text_field( $_POST['customer_name'] );

update_post_meta( 2, 'customer_name', $clean_name );

printf( 'Stored customer name: %s', esc_html( get_post_meta( 2, 'customer_name', true ) ) );

sanitize_text_field only cleans the string; it does not check capabilities or verify a nonce, so a real form handler still needs those checks.

Clean up a comma-separated tag list before assigning it to a post

A raw string typed into a plugin's admin field can carry tabs and line breaks that should collapse before the tags are split apart.

$raw_tags = "news, \tupdates\n, featured";

$clean_tags = sanitize_text_field( $raw_tags );

$tag_names = array_map( 'trim', explode( ',', $clean_tags ) );

wp_set_post_tags( 1, $tag_names, true );

print_r( wp_get_post_tags( 1, array( 'fields' => 'names' ) ) );

wp_set_post_tags still needs valid or existing term names; sanitize_text_field only tidies the raw string, it does not validate the terms.

Common problems and fixes · 4

Why do my line breaks disappear when I sanitize a textarea value with this function?

The source calls _sanitize_text_fields( $str, false ), and that trailing false tells the internal helper not to preserve newlines, so multi-line input gets collapsed to a single line.

Why did part of my string vanish when it contained something like %20 or %3D?

The long description states the function strips percent-encoded characters. Any substring that looks like URL-encoding is removed outright rather than decoded, which can eat legitimate text such as a literal percent sign followed by digits.

Is it safe to echo the result of sanitize_text_field() straight into HTML?

It converts a single < character to an entity and strips tags, but it is not a general HTML-escaping function; it does not encode ampersands or quotes the way esc_html() does, so output can still be unsafe in some contexts.

Can a plugin change what sanitize_text_field() returns?

Yes. The function passes its cleaned value through the sanitize_text_field filter before returning, and any plugin hooked there can alter or replace $filtered.

Alternatives and related functions

sanitize_textarea_field
When the input is multi-line, such as a comment or message, and line breaks need to survive sanitizing.
wp_strip_all_tags
When all that's needed is tag stripping without the whitespace collapsing and percent-encoding removal sanitize_text_field also performs.
sanitize_title
When the string will be used as a slug or URL segment rather than displayed as plain text.
esc_html
When the goal is safe HTML output rather than cleaning up raw input before storage.

Performance profile

How much work a call to sanitize_text_field() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Trivial

Touches nothing outside its own arguments.

Scaling
Constant

No loop in the body: the same number of instructions runs whatever you pass in.

Instructions
12

Executed per call on PHP 8.5. The body compiles to 12.

Plugin surface
1 hook

Third-party callbacks on 'sanitize_text_field' run inside this call, and their cost is not bounded by anything here.

Called by
50

50 places in core call this, so the cost is paid more often than your own code shows.

What it touches

  • hookthird-party callbacksapply_filters()called directly

Further down the call graph this can also reach option, cache, serialize, query and transient. Those are the worst case, several calls deep and usually down an error path, not what a normal call pays.

What one call costs · 1 distinct outcome

One number would be a lie: the work depends on which branch runs. These are every distinct cost sanitize_text_field() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
always12_sanitize_text_fields(), apply_filters()

Across PHP versions

Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 12 instructions, 12 executed per call, 0 branches. The work does not change between versions.

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Hooks and filters fired · 1

One hook fires while sanitize_text_field() runs, in this order:

  1. apply_filters( sanitize_text_field )filterline 5585 (+11 into the body)

    Filters a sanitized text field string.

Uses · 2

Used by · 50

Show all 50

Source code

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 );}

Changelog

Introduced in 2.9.0. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

About this page

Parsed data
Generated from the wordpress-develop 6.8.8 tag, from src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.