34

Possible Duplicate:
remove multiple whitespaces in php

I have a stream of characters, a sentence or a paragraph, which may have extra spaces in two words or even tabs or line feeds, how can I remove all these and substitute them by a single whitespace.

Community
  • 1
  • 1
Kumar
  • 5,038
  • 7
  • 39
  • 51
  • How could that question skip my eyes? Thanks Shakti :-) – Kumar Apr 04 '11 at 13:39
  • The question is not quite the same as the one @Shakti has marked as duplicate. Perhaps it's just a misunderstanding, though. What do you want to happen to a *single* tab or line feed character? Should they be left alone? Should multiple tabs become one single tab, or should they become one single blank? What about mixed tabs, spaces, newlines etc.? – Tim Pietzcker Apr 04 '11 at 13:48
  • @Tim Pietzcker, I want to convert all white spaces, tabs and linefeeds to one white space, so that I can then `explode()` the sentence using white space as delimiter. – Kumar Apr 04 '11 at 14:25
  • So you mean "convert to space" (ASCII 32) not "white space" (space, line feed, tab, form feed etc.). OK. Then jeroen's solution is the right one for you. – Tim Pietzcker Apr 04 '11 at 14:27
  • well, isn't white space = ASCII 32 space? Correct me if I am wrong. I don't want non breaking (white) space. – Kumar Apr 04 '11 at 14:33

1 Answers1

109

You could use a regular expression like:

preg_replace("/\s+/", " ", $string);

That should replace all multiple white-spaces, tabs and new-lines with just one.

Thanks to @ridgerunner for the suggestion - it can significantly faster if you add the 'S' study modifier:

preg_replace('/\s+/S', " ", $string);

'S' helps "non-anchored patterns that do not have a single fixed starting character" - i.e. a character class.

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132