How to Strip all Spaces out of a String in PHP
If you want to get the best solution to how to strip all spaces out of a string in PHP, you are in the right place. Read the snippet and choose your option.
In this tutorial, we present 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:
php str_replace
<?php
$string = 'hello world';
$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:
php preg_replace
<?php
$string = 'hello world';
$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 either a string or an array, along with all the occurrences of the search in subject replaced with the exact replace value.
Describing the preg_replace Function
preg_replace is used for implementing a regular expression search and replacement.
It is capable of returning either an array or a string.