normalize_whitespace()
Standardizes (unifies) line break characters (EOL) in the provided string: converts all breaks to a single form \n. Also, it removes spaces at the ends and multiple spaces.
The function can be useful, for example, when you need to compare two contents that may differ only by spaces or line breaks (including at the ends of the string).
1 time — 0.000123 sec (fast) | 50000 times — 0.04 sec (speed of light)
No Hooks.
Returns
String. Processed string.
Usage
normalize_whitespace( $str );
- $str(string) (required)
- String to normalize.
Examples
#1 Normalizing a string with spaces
$string = 'hello world '; // 18 characters with a space at the end string = normalize_whitespace( $string ); //> 'hello world' // 11 characters without a space at the end
#2 Line Comparison
Suppose we have saved the content entered into a text field and we want to periodically compare whether it is different from the current content in the field.
$autosave_is_different = false;
if( normalize_whitespace( $current_content ) !== normalize_whitespace( $saved_content ) ) {
$autosave_is_different = true;
}
Changelog
| Since 2.7.0 | Introduced. |
normalize_whitespace() normalize whitespace code WP 6.8.3
function normalize_whitespace( $str ) {
$str = trim( $str );
$str = str_replace( "\r", "\n", $str );
$str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
return $str;
}