开发者

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

开发者 https://www.devze.com 2023-02-22 11:08 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: remove multiple whitespaces in php
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消