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
RemovingallthespacesiseasywithPHP
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
Removingallthespaces,andtabsiseasywithPHP
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
Removingallthespaces,newlines,andtabsiseasywithPHP
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