Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

+12025550123

Any whitespace

The \s+ regular expression removes tabs and line breaks as well:

<?php
 
echo preg_replace('/\s+/', '', "a b\tc\nd");

Output:

abcd

Leaving single spaces

To collapse repeats, replace them with one space:

<?php
 
echo preg_replace('/\s+/', ' ', trim("  too    many   spaces  "));

Output:

too many spaces

Functions 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.

Thanks for reading!

Donate to the site — we work hard for you.