How do I strip all spaces out of a string in PHP?
Last Updated on Dec 13, 2022 - Written By Torikul Islam
You can strip spaces from a string using str_replace()
function. It is an PHP built-in function.
In the process of removing spaces, you need to understand the type of spaces first. Because some of them could include tabs and line ends, or could include
in HTML.
For normal spaces, use str_replace()
Syntax
str_replace('substring', 'replaced_string', 'original_string');
Or
preg_replace('substring', 'replaced_string', 'original_string');
We need to provide three parameters.
1. Substring is the first parameter which should be replaced with replaced_string.
2. Replaced_string will replace the substring.
3. Original_string will contain the full string from where you want to strip spaces.
In the placement of parameters, you can use PHP variables.
Examples of strip spaces from a string
You will see here different application on different examples.
Example 1: Remove simple spaces
<?php
//input string
$string = 'This is my string.
This is an example of string.';
//strip simple spaces
$string = str_replace(' ', '', $string);
//showing result
echo $string;
?>
Output:
Thisismy string. Thisisanexampleofstring.
But this solution do not stripped all spaces. Because it just removed normal spaces.
Example 2: Remove spaces including line brakes
<?php
//input string
$string = 'This is my string.
This is an example of string.';
//removing whitespaces using regex
$string = preg_replace('/\s+/', '', $string);
//showing result
echo $string;
?>
Output:
Thisismy string.Thisisanexampleofstring.
And it doesn’t removed from string. That is why we still see an space.
Example 3: Remove HTML character NBSP
NBSP or Non Breaking Space is an HTML character. It is not like typical space, but it tells browser to show a space for every
. So, while you need to remove this kind of spaces, you need to remove this character.
<?php
//input string
$string = 'This is my string.';
//removing spaces for html character
$string = str_replace(' ', '', $string);
//showing result
echo $string;
?>
Output:
Thisismystring.