235

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

487

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.

Sign up to request clarification or add additional context in comments.

8 Comments

@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: 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.
/\s{2,}/u' - if you have some UTF-8 problem add /u switch
for unicode there is mb_ereg_replace doc
This should not be correct answer, as it removes all the newlines as well, question is about spaces...
|
84
$output = preg_replace('/\s+/', ' ',$input);

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

Comments

53
preg_replace("/[[:blank:]]+/"," ",$input)

5 Comments

Doesn't replace "\n" (PHP 5.3), "/\s+/" get's job done. ;)
Actually this helped, \s messed up my multibyte word, replaceing Š with some kind of square.
@MārtiņšBriedis There is separate multibyte function: php.net/manual/en/function.mb-ereg-replace.php
Unlike other answers, this command only replaces spaces (not newlines, etc...), which is exactly what is needed! Thank you so much!
The code for multibyte encoding would be mb_ereg_replace('[[:blank:]]+', ' ', $input)or mb_ereg_replace('\s+', ' ', $input) depending on the use case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.