How to strip all spaces out of a string in php
How to strip all spaces out of a string in php
You have a string stored in a PHP variable, and you want to eliminate all whitespaces or spaces from that string with PHP, not only from the beginning or the end of the string.
Scenario
1 2 3 4 5 6 |
<?php //You want to strip all spaces from the below string and obtain "thisisjustastring" $firstString= 'this is just a string'; ?> |
Solution for spaces
1 2 3 4 5 6 7 |
<?php $firstString= 'this is just a string'; $newString = str_replace(' ', '', $firstString); echo $newString; //outputs "thisisjustastring" as a string ?> |
Solution for whitespaces
1 2 3 4 5 6 7 |
<?php $firstString= 'this is just a string'; $newString = preg_replace('/\s+/', '', $firstString); echo $newString //outputs "thisisjustastring" as a string ?> |
Difference between spaces and whitespaces
Space is the regular space character between words, whitespace is any kind of space in text: regular space, new line, tab, etc. Their ASCII representation differs one from another, this is why we need different solutions for them.