Remove excess whitespace from a string in PHP
This article demonstrates how to remove excess whitespace from a string in PHP.
You can remove excess whitespace from a string using a regular expression. In order to replace one or more whitespace characters with a single whitespace character, you can use the regex \s+. The \s matches a single whitespace character, including space, tab, form feed, line feed, and other Unicode spaces, and the + matches the preceding item 1 or more times. Therefore, the pattern \s+ matches 1 or more whitespace characters.
The following solution replaces the consecutive whitespace characters with a single space using the preg_replace() method. Note that it does not remove leading and trailing whitespace characters from the string.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $text = ' Brooklyn St, NY, 14001'; $result = preg_replace('/\s+/', ' ', $text); echo "\"$result\""; /* Output: " Brooklyn St, NY, 14001" */ ?> |
If you want to strip all whitespace from the beginning or the end of a string, you can use the ltrim() and rtrim() functions, respectively. To remove both leading and trailing whitespace from a string, consider using the trim() function. The following code removes extra spaces, along with all leading and trailing spaces.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $text = ' Brooklyn St, NY, 14001'; $result = preg_replace('/\s+/', ' ', trim($text)); echo "\"$result\""; /* Output: "Brooklyn St, NY, 14001" */ ?> |
That’s all about removing excess whitespace from a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)