How to Strip all Spaces out of a String in PHP

In this tutorial, we represent to you the most efficient ways of stripping all spaces out of a string in PHP. Below you can find the options depending on the exact requirements.

A. Applying str_replace for Only Spaces

If your goal is to strip just spaces out of a string, then you can use str_replace as shown below:


$string = str_replace(' ', '', $string);


B. Applying preg_replace for Whitespace

In case you are interested in stripping whitespace, as well as line ends and tabs, then you need to implement preg_replace like this:


$string = preg_replace('/\s+/', '', $string);


Describing the str_replace Function

The str_replace function is used for replacing all the occurrences of the search string with replacement strings. It can return a string either an array, along with all the occurrences of the search in subject replaced with the exact replace value.

Describing the preg_replace

preg_replace is used for implementing a regular expression search and replacement.

It is capable of returning either an array or a string.