php 如何从句子中删除多余的空格、制表符和换行符,并将它们替换为一个空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5539169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove extra spaces, tabs and line feeds from a sentence and substitute them with just one space?
提问by Kumar
Possible Duplicate:
remove multiple whitespaces in php
可能的重复:
删除 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.
我有一个字符流、一个句子或一个段落,其中两个单词甚至制表符或换行符中可能有多余的空格,我如何删除所有这些并用单个空格替换它们。
回答by jeroen
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 @ridgerunnerfor the suggestion - it can significantly faster if you add the 'S'
study modifier:
感谢@ridgerunner的建议 - 如果您添加'S'
研究修改器,它可以显着加快:
preg_replace('/\s+/S', " ", $string);