Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove extra spaces, tabs and line feeds from a sentence and substitute them with just one space? [duplicate]

Tags:

regex

php

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.

like image 950
Kumar Avatar asked Apr 04 '11 13:04

Kumar


People also ask

How do you remove extra spaces from a string?

To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext. replaceAll("( )+", " ") .


1 Answers

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.

like image 126
jeroen Avatar answered Sep 28 '22 07:09

jeroen