This article demonstrates how to strip all spaces from a string in PHP.

1. Using str_replace() function

The str_replace() function is used to replace all occurrences of the search string with the replacement string. To remove all spaces from the string, you can use space (" ") as the search string and an empty string ("") as the replacement string.

Download  Run Code

 
The above solution only removes the space character from the string. However, it doesn’t remove any other type of whitespace character, which is composed of spaces, tabs, or line breaks. In order to remove all whitespace from the string, you would have to invoke the str_replace() function multiple times, once for each whitespace character.

Download  Run Code

2. Using preg_replace() function

To strip all whitespace characters from the string, you can use the regular expression \s+ which matches one or more whitespace characters. In PHP, you can use the preg_replace() function to perform search and replace using a regex.

Download  Run Code

 
You can extend the above solution to remove only excess whitespace from a string. The following solution replaces consecutive whitespace characters with a single space, and also removes all leading and trailing whitespace from the string with trim() function.

Download  Run Code

That’s all about stripping all spaces from a string in PHP.