如何从句子中删除多余的空格,制表符和换行符,并用一个空格替换它们? [重复]

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.

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.