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.

Download  Run Code

 
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.

Download  Run Code

That’s all about removing excess whitespace from a string in PHP.