How to remove all whitespace from a string
Short answer
str_replace() removes plain spaces:
<?php
echo str_replace(' ', '', '+1 202 555 01 23');Output:
+12025550123Any whitespace
The \s+ regular expression removes tabs and line breaks as well:
<?php
echo preg_replace('/\s+/', '', "a b\tc\nd");Output:
abcdLeaving single spaces
To collapse repeats, replace them with one space:
<?php
echo preg_replace('/\s+/', ' ', trim(" too many spaces "));Output:
too many spacesFunctions used in this recipe
- preg_replace — Replaces everything that matches a regular expression.
- str_replace — Replaces all occurrences of a substring with another string.
- trim — Removes whitespace and other characters from both ends of a string.