normalize_whitespace()
Normalize EOL characters and strip duplicate whitespace.
1 time — 0.000123 sec (fast) | 50000 times — 0.04 sec (speed of light)
No Hooks.
Return
String
. The normalized string.
Usage
normalize_whitespace( $str );
- $str(string) (required)
- The 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.7.1
function normalize_whitespace( $str ) { $str = trim( $str ); $str = str_replace( "\r", "\n", $str ); $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str ); return $str; }