Using WordPress ‘normalize_whitespace()’ PHP function

The normalize_whitespace() WordPress PHP function normalizes end-of-line characters and strips duplicate whitespace from a given string.


normalize_whitespace( $str )



normalize_whitespace("  This   is a  sample   text.  ")


"This is a sample text."


  • $str (string) – The string you want to normalize by removing extra whitespaces.

More information

See WordPress Developer Resources: normalize_whitespace()


Normalize user input

Normalize user input for display or processing.

$user_input = "   My name  is    John   Doe.  ";
$normalized_input = normalize_whitespace($user_input);
echo $normalized_input; // Output: "My name is John Doe."

Normalize file content

Normalize the content of a file before processing or displaying it.

$file_content = "This is  some  content\nfrom a  text   file.";
$normalized_content = normalize_whitespace($file_content);
echo $normalized_content; // Output: "This is some content from a text file."

Normalize user-generated content

Normalize user-generated content before saving it to the database.

$post_content = "   This is a   user-generated   post.  ";
$normalized_post_content = normalize_whitespace($post_content);
// Save $normalized_post_content to the database

Normalize text for comparison

Normalize text before comparing strings to ensure accurate results.

$string1 = "This  is a  test  string.";
$string2 = "This is a test string.";
$normalized_string1 = normalize_whitespace($string1);
$normalized_string2 = normalize_whitespace($string2);

if ($normalized_string1 === $normalized_string2) { echo "Strings are equal."; } else { echo "Strings are not equal."; } // Output: "Strings are equal."

Normalize CSV data

Normalize CSV data before processing or importing it.

$csv_data = "Name,  Age,  Gender\nJohn  Doe,   30,  Male";
$normalized_csv_data = normalize_whitespace($csv_data);
echo $normalized_csv_data; // Output: "Name, Age, Gender John Doe, 30, Male"