I'm trying to remove excess whitespace from a string like this:
hello world
to
hello world
Anyone has any idea how to do that in PHP?
The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
More Detail. The ctype_space() function in PHP check for whitespace character(s). It returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.
With a regexp :
preg_replace('/( )+/', ' ', $string);
If you also want to remove every multi-white characters, you can use \s (\s is white characters)
preg_replace('/(\s)+/', ' ', $string);
$str = 'Why do I
have so much white space?';
$str = preg_replace('/\s{2,}/', ' ', $str);
var_dump($str); // string(34) "Why do I have so much white space?"
See it!
You could also use the +
quantifier, because it always replaces it with a . However, I find
{2,}
to show your intent clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With