How do You Remove all Whitespace From a String in PHP With Example?

You can remove all whitespace from a string in PHP using various methods. Here’s one way to do it using the `preg_replace()` function with a regular expression:

$string = " Hello World ";

// Remove all whitespace using regular expression
$cleanString = preg_replace('/\s+/', '', $string);

echo "Original String: '" . $string . "'<br>";

echo "Cleaned String: '" . $cleanString . "'";

This code will output:

Original String: ' Hello World '
Cleaned String: 'HelloWorld'


1. `’/\s+/’`: This regular expression matches one or more whitespace characters (including spaces, tabs, and newlines).
2. `preg_replace(‘/\s+/’, ”, $string)`: This function replaces all occurrences of whitespace characters with an empty string, effectively removing them from the original string.
3. `$cleanString`: This variable holds the cleaned string without any whitespace.