232

I'm trying to replace multiple spaces with a single space. When I use ereg_replace, I get an error about it being deprecated.

ereg_replace("[ \t\n\r]+", " ", $string);

Is there an identical replacement for it. I need to replace multiple " " white spaces and multiple nbsp white spaces with a single white space.

0

3 Answers 3

481

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

8
  • 1
    @Cletus: This one would replace a single space with space. Don't you think something like: preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x) will be more efficient especially on text with several single spaces ?
    – codaddict
    Commented Mar 3, 2010 at 4:23
  • 31
    @codaddict: by chance, a moment ago i benchmarked those on real-life data, result (for calls on ~8300 various text articles): /(?:\s\s+|\n|\t)/ => 1410 (slowest), /\s+/ => 611 (ok'ish), /\s\s+/ => 496 (fastest). The last one does not replace single \n or \t, but thats ok for my case.
    – Frunsi
    Commented Dec 16, 2011 at 2:09
  • 20
    /\s{2,}/u' - if you have some UTF-8 problem add /u switch
    – user956584
    Commented May 28, 2012 at 9:09
  • 1
    for unicode there is mb_ereg_replace doc
    – gondo
    Commented Feb 28, 2016 at 19:04
  • 2
    This should not be correct answer, as it removes all the newlines as well, question is about spaces...
    – prk_001
    Commented Jan 10, 2020 at 11:50
84
$output = preg_replace('/\s+/', ' ',$input);

\s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

0
53
preg_replace("/[[:blank:]]+/"," ",$input)
5
  • 6
    Doesn't replace "\n" (PHP 5.3), "/\s+/" get's job done. ;)
    – Marek
    Commented Sep 4, 2013 at 8:21
  • 1
    Actually this helped, \s messed up my multibyte word, replaceing Š with some kind of square. Commented Jun 24, 2015 at 9:38
  • 1
    @MārtiņšBriedis There is separate multibyte function: php.net/manual/en/function.mb-ereg-replace.php Commented Oct 3, 2016 at 13:03
  • 3
    Unlike other answers, this command only replaces spaces (not newlines, etc...), which is exactly what is needed! Thank you so much!
    – itoctopus
    Commented Oct 23, 2019 at 12:21
  • The code for multibyte encoding would be mb_ereg_replace('[[:blank:]]+', ' ', $input)or mb_ereg_replace('\s+', ' ', $input) depending on the use case.
    – Pjotr
    Commented Jan 25 at 14:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.