esc_textarea()
云策文档标注
概述
esc_textarea() 是 WordPress 中用于转义文本区域值的函数,确保输出到 textarea 元素中的内容安全,防止跨站脚本攻击。它基于博客字符集使用 htmlspecialchars 进行转义,并可通过过滤器进行自定义。
关键要点
- 函数 esc_textarea( $text ) 接受一个必需字符串参数 $text,返回转义后的字符串。
- 使用 htmlspecialchars 进行转义,设置 ENT_QUOTES 以转义单双引号,字符集通过 get_option( 'blog_charset' ) 获取。
- 提供过滤器 'esc_textarea',允许开发者修改转义后的字符串,参数为 $safe_text 和原始 $text。
- 函数自 WordPress 3.1.0 版本引入,常用于输出到 textarea 元素的场景,如小部件表单和自定义控件。
代码示例
function esc_textarea( $text ) {
$safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
/**
* Filters a string cleaned and escaped for output in a textarea element.
*
* @since 3.1.0
*
* @param string $safe_text The text after it has been escaped.
* @param string $text The text prior to being escaped.
*/
return apply_filters( 'esc_textarea', $safe_text, $text );
}注意事项
- 此函数主要用于 textarea 元素,但根据用户贡献笔记,可能具有更广泛的适用性,建议参考相关文档链接。
- 转义时需确保字符集设置正确,以避免乱码或安全问题。
原文内容
Escaping for textarea values.
Parameters
$textstringrequired
Source
function esc_textarea( $text ) {
$safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
/**
* Filters a string cleaned and escaped for output in a textarea element.
*
* @since 3.1.0
*
* @param string $safe_text The text after it has been escaped.
* @param string $text The text prior to being escaped.
*/
return apply_filters( 'esc_textarea', $safe_text, $text );
}
Hooks
- apply_filters( ‘esc_textarea’, string $safe_text, string $text )
-
Filters a string cleaned and escaped for output in a textarea element.
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |
Skip to note 2 content
Michael Nelson
It seems this function may have wider applicability than its name indicates, please see https://developer.wordpress.org/reference/functions/esc_attr/#comment-2473