函数文档

_sanitize_text_fields()

💡 云策文档标注

概述

_sanitize_text_fields() 是 WordPress 内部辅助函数,用于对用户输入或数据库中的字符串进行清理,确保安全性和有效性。

关键要点

  • 函数接受两个参数:必需参数 $str(要清理的字符串)和可选参数 $keep_newlines(是否保留换行符,默认为 false)。
  • 返回清理后的字符串,如果输入是对象或数组,则返回空字符串。
  • 内部调用 wp_check_invalid_utf8() 检查无效 UTF-8 编码,并使用 wp_strip_all_tags() 去除所有 HTML 标签。
  • 被 sanitize_text_field() 和 sanitize_textarea_field() 等函数使用,自 WordPress 4.7.0 版本引入。

代码示例

function _sanitize_text_fields( $str, $keep_newlines = false ) {
	if ( is_object( $str ) || is_array( $str ) ) {
		return '';
	}

	$str = (string) $str;

	$filtered = wp_check_invalid_utf8( $str );

	if ( str_contains( $filtered, '<' ) || str_contains( $filtered, '>' ) ) {
		$filtered = wp_strip_all_tags( $filtered, $keep_newlines );
	}

	return trim( $filtered );
}

注意事项

  • 此函数是内部辅助函数,通常不直接调用,而是通过 sanitize_text_field() 或 sanitize_textarea_field() 使用。
  • 相关函数包括 wp_strip_all_tags()、wp_pre_kses_less_than() 和 wp_check_invalid_utf8(),用于处理字符串清理的不同方面。

📄 原文内容

Internal helper function to sanitize a string from user input or from the database.

Parameters

$strstringrequired
String to sanitize.
$keep_newlinesbooloptional
Whether to keep newlines. Default: false.

Default:false

Return

string Sanitized string.

Source

function _sanitize_text_fields( $str, $keep_newlines = false ) {
	if ( is_object( $str ) || is_array( $str ) ) {
		return '';
	}

	$str = (string) $str;

	$filtered = wp_check_invalid_utf8( $str );

	if ( str_contains( $filtered, '<' ) ) {
		$filtered = wp_pre_kses_less_than( $filtered );
		// This will strip extra whitespace for us.
		$filtered = wp_strip_all_tags( $filtered, false );

		/*
		 * Use HTML entities in a special case to make sure that
		 * later newline stripping stages cannot lead to a functional tag.
		 */
		$filtered = str_replace( "<n", "<n", $filtered );
	}

	if ( ! $keep_newlines ) {
		$filtered = preg_replace( '/[rnt ]+/', ' ', $filtered );
	}
	$filtered = trim( $filtered );

	// Remove percent-encoded characters.
	$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 percent-encoded characters.
		$filtered = trim( preg_replace( '/ +/', ' ', $filtered ) );
	}

	return $filtered;
}

Changelog

Version Description
4.7.0 Introduced.