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.
To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext. replaceAll("( )+", " ") .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With