The Best Way To Strip All Spaces Out of a String in PHP

How do I strip all spaces out of a string in PHP? The solution is easier than you might think, let's explore.

To remove all spaces using PHP, we can use the str_replace function. The string replace function in PHP is great for changing characters in a string.

Removing spaces with PHP

$string = 'Removing all the spaces is easy with PHP';
echo str_replace(' ', '', $string);

# Outputs

We can also PHP's preg_replace() function to remove spaces. We pass three parameters, the first is the regex search string, the second is what we want to replace it with (which is nothing), and finally, the string we're processing this regular expression on.

$string = "Removing all the spaces is easy with PHP";
echo preg_replace('/ /', '', $string);

We can take this function one step further, and replace all spaces and tabs in one go.

$string = "Removing all the spaces, \t\t and tabs is easy with \tPHP";
echo preg_replace('/\s/', '', $string);

# Outputs

If our string has new lines, we can remove those too, by updating our regular expression.

$string = "Removing all the spaces,\n new lines, \t\t and tabs is easy with \tPHP";
echo preg_replace('/\s+/', '', $string);

# Outputs

A common requirement went building web applications is removing space from the start and end of the string. To do that we can use PHP's trim function.

$string = " Remove the spaces at the start and end of this string ";
echo trim($string);

# Outputs
Remove the spaces at the start and end of this string

Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Related Dev Guides

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.

Reject non-essential Accept all