How to Remove Whitespace from String in PHP Easily
trim() to remove spaces from the start and end, or str_replace() and preg_replace() to remove all spaces inside the string. These functions help clean up strings by removing unwanted spaces.Syntax
trim(): Removes whitespace from the beginning and end of a string.
str_replace(): Replaces all occurrences of a substring (like spaces) with another string (like empty).
preg_replace(): Uses patterns to remove all whitespace characters including spaces, tabs, and newlines.
$cleaned = trim($string); $cleaned = str_replace(' ', '', $string); $cleaned = preg_replace('/\s+/', '', $string);
Example
This example shows how to remove whitespace from a string using trim(), str_replace(), and preg_replace(). It demonstrates removing spaces from the start/end, all spaces, and all whitespace characters.
<?php $string = " Hello World \n "; // Remove whitespace from start and end $trimmed = trim($string); // Remove all spaces inside the string $noSpaces = str_replace(' ', '', $string); // Remove all whitespace characters (spaces, tabs, newlines) $noWhitespace = preg_replace('/\s+/', '', $string); // Output results echo "Original: '" . $string . "'\n"; echo "Trimmed: '" . $trimmed . "'\n"; echo "No spaces: '" . $noSpaces . "'\n"; echo "No whitespace: '" . $noWhitespace . "'\n"; ?>
Common Pitfalls
One common mistake is using trim() expecting it to remove spaces inside the string, but it only removes spaces at the start and end. Another is forgetting that str_replace(' ', '') removes only space characters, not tabs or newlines. To remove all whitespace characters, use preg_replace('/\s+/', '').
<?php // Wrong: only trims edges, does not remove spaces inside $wrong = trim(' Hello World '); // Right: removes all spaces inside $right = str_replace(' ', '', ' Hello World '); // Best: removes all whitespace including tabs and newlines $best = preg_replace('/\s+/', '', " Hello \t World \n "); // Outputs var_dump($wrong); // string(11) "Hello World" var_dump($right); // string(10) "HelloWorld" var_dump($best); // string(10) "HelloWorld"
Quick Reference
| Function | Purpose | Removes |
|---|---|---|
| trim($string) | Removes whitespace from start and end | Spaces, tabs, newlines at edges |
| str_replace(' ', '', $string) | Removes all space characters | Spaces only, anywhere |
| preg_replace('/\s+/', '', $string) | Removes all whitespace characters | Spaces, tabs, newlines anywhere |