函数文档

normalize_whitespace()

💡 云策文档标注

概述

normalize_whitespace() 是一个 WordPress 核心函数,用于规范化字符串中的空白字符。它主要处理换行符和重复空格,确保字符串格式一致。

关键要点

  • 函数接受一个字符串参数 $str,返回规范化后的字符串。
  • 功能包括:去除首尾空格、统一换行符为 、压缩连续换行符和空格。
  • 常用于处理文本数据,如自动保存、修订和文本差异比较等场景。

代码示例

function normalize_whitespace( $str ) {
	$str = trim( $str );
	$str = str_replace( "r", "n", $str );
	$str = preg_replace( array( '/n+/', '/[ t]+/' ), array( "n", ' ' ), $str );
	return $str;
}

注意事项

  • 函数自 WordPress 2.7.0 版本引入,属于核心功能。
  • 相关函数包括 WP_REST_Autosaves_Controller::create_post_autosave()、wp_create_post_autosave() 等,用于自动保存和修订处理。

📄 原文内容

Normalizes EOL characters and strips duplicate whitespace.

Parameters

$strstringrequired
The string to normalize.

Return

string The normalized string.

Source

function normalize_whitespace( $str ) {
	$str = trim( $str );
	$str = str_replace( "r", "n", $str );
	$str = preg_replace( array( '/n+/', '/[ t]+/' ), array( "n", ' ' ), $str );
	return $str;
}

Changelog

Version Description
2.7.0 Introduced.