wp_remove_surrounding_empty_script_tags()
云策文档标注
概述
wp_remove_surrounding_empty_script_tags() 是一个辅助函数,用于移除内联脚本周围字面量的空 script 标签。它主要用于 wp_get_inline_script_tag() 或 wp_print_inline_script_tag() 中,常与输出缓冲结合使用。
关键要点
- 移除字符串开头和结尾的字面量空 script 标签(即 "<script>" 和 "</script>"),在修剪空白后执行。
- 如果字符串不精确匹配这些字面量,函数会触发 _doing_it_wrong() 警告并返回一个 JavaScript console.error 调用。
- 主要用于输出缓冲场景,例如将 ob_get_clean() 的结果作为 $contents 参数传递。
代码示例
// 移除精确的空 SCRIPT 标签字面量
$js = '<script>sayHello();</script>';
'sayHello();' === wp_remove_surrounding_empty_script_tags( $js );
// 否则,如果内容不同,会在 JS 控制台警告
$js = '<script type="text/javascript">console.error( ... )</script>';
'console.error( ... )' === wp_remove_surrounding_empty_script_tags( $js );注意事项
- 函数仅移除字面量空 script 标签,不处理带属性的 script 标签或其他内容。
- 使用时需确保 $contents 参数是字符串,且开头和结尾精确匹配 "<script>" 和 "</script>",否则会触发错误处理。
- 自 WordPress 6.4.0 版本引入,是较新的辅助功能。
原文内容
Removes leading and trailing _empty_ script tags.
Description
This is a helper meant to be used for literal script tag construction within wp_get_inline_script_tag() or wp_print_inline_script_tag().
It removes the literal values of “” and “” from around an inline script after trimming whitespace. Typically this is used in conjunction with output buffering, where ob_get_clean() is passed as the $contents argument.
Example:
// Strips exact literal empty SCRIPT tags.
$js = '<script>sayHello();</script>;
'sayHello();' === wp_remove_surrounding_empty_script_tags( $js );
// Otherwise if anything is different it warns in the JS console.
$js = '<script type="text/javascript">console.log( "hi" );</script>';
'console.error( ... )' === wp_remove_surrounding_empty_script_tags( $js );
See also
Parameters
$contentsstringrequired-
Script body with manually created SCRIPT tag literals.
Source
function wp_remove_surrounding_empty_script_tags( $contents ) {
$contents = trim( $contents );
$opener = '<SCRIPT>';
$closer = '</script>';
if (
strlen( $contents ) > strlen( $opener ) + strlen( $closer ) &&
strtoupper( substr( $contents, 0, strlen( $opener ) ) ) === $opener &&
strtoupper( substr( $contents, -strlen( $closer ) ) ) === $closer
) {
return substr( $contents, strlen( $opener ), -strlen( $closer ) );
} else {
$error_message = __( 'Expected string to start with script tag (without attributes) and end with script tag, with optional whitespace.' );
_doing_it_wrong( __FUNCTION__, $error_message, '6.4' );
return sprintf(
'console.error(%s)',
wp_json_encode(
sprintf(
/* translators: %s: wp_remove_surrounding_empty_script_tags() */
__( 'Function %s used incorrectly in PHP.' ),
'wp_remove_surrounding_empty_script_tags()'
) . ' ' . $error_message
)
);
}
}
Changelog
| Version | Description |
|---|---|
| 6.4.0 | Introduced. |