函数文档

sanitize_text_field()

💡 云策文档标注

概述

sanitize_text_field() 是 WordPress 核心函数,用于对来自用户输入或数据库的字符串进行清理,确保其安全性和一致性。它通过检查无效 UTF-8、移除 HTML 标签、转换特殊字符等方式处理字符串,常用于表单数据、API 输入等场景。

关键要点

  • 清理字符串,检查无效 UTF-8 编码
  • 转换单引号等特殊字符为 HTML 实体
  • 移除所有 HTML 标签
  • 删除换行符、制表符和多余空白
  • 去除百分号编码字符
  • 仅处理字符串,不适用于数组(需使用 map_deep 或递归函数)
  • 不能防止 SQL 注入,数据库查询应使用 wpdb::prepare()
  • 通过 sanitize_text_field 过滤器可自定义清理逻辑

代码示例

// 基本用法
$unsafe_input = 'alert("XSS")hello';
$safe_input = sanitize_text_field($unsafe_input);
echo $safe_input; // 输出: hello

// 清理数组(使用 map_deep)
$form_data = array('key' => 'value');
$sanitized_array = map_deep($form_data, 'sanitize_text_field');

// 或使用 array_map
$sanitized_array = array_map('sanitize_text_field', $array);

注意事项

  • sanitize_text_field() 仅适用于字符串,处理数组需额外方法如 map_deep() 或递归函数
  • 不提供 SQL 注入防护,数据库操作应结合 wpdb::prepare()
  • 函数自 WordPress 2.9.0 引入,广泛用于核心和插件开发
  • 相关函数包括 sanitize_textarea_field()、wp_check_invalid_utf8()、wp_strip_all_tags()

📄 原文内容

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

See also

Parameters

$strstringrequired
String to sanitize.

Return

string Sanitized string.

More Information

Basic Usage

Source

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

Hooks

apply_filters( ‘sanitize_text_field’, string $filtered, string $str )

Filters a sanitized text field string.

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    Check whether the string is a valid UTF-8 character, and remove all HTML tags.

    $str = "<h2>Title</h2>";
    sanitize_text_field( $str ); // it will return "title" without any HTML tags!

  2. Skip to note 9 content

    I ran across an issue with one of my plugins, as it was going through the initial security review, where I had an array that wasn’t passing a security check. The sanitize_text_field() function only works on a string, not an array’d item.

    I located this nice little tidbit of code to sanitize an array, properly.

    /***
     * To ensure arrays are properly sanitized to WordPress Codex standards,
     * they encourage usage of sanitize_text_field(). That only works with a single
     * variable (string). This function allows for a full blown array to get sanitized
     * properly, while sanitizing each individual value in a key -> value pair.
     *
     * Source: <a href="https://wordpress.stackexchange.com/questions/24736/wordpress-sanitize-array" rel="nofollow ugc">https://wordpress.stackexchange.com/questions/24736/wordpress-sanitize-array</a>
     * Author: Broshi, answered Feb 5 '17 at 9:14
     */
    function wporg_recursive_sanitize_text_field( $array ) {
    	foreach ( $array as $key => &$value ) {
    		if ( is_array( $value ) ) {
    			$value = wporg_recursive_sanitize_text_field( $value );
    		} else {
    			$value = sanitize_text_field( $value );
    		}
    	}
    	return $array;
    }

    IMHO, this needs to become a core feature of WordPress’ sanitation functions. Lior Broshi is the gentleman that came up with this creative solution (I have obtained his permission to share this).

  3. Skip to note 10 content

    <br />
    $unsafe_input = 'alert("XSS")hello';<br />
    $safe_input = sanitize_text_field($unsafe_input);<br />
    echo $safe_input; // Output: hello<br />

    Use sanitize_text_field() when:
    (1) You’re handling free-form user input from forms, URLs, or APIs.
    (2) The value will be stored in the database, output in HTML, or used in queries.