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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:45:52  来源:igfitidea点击:

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

phpregex

提问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);

'S'helps "non-anchored patterns that do not have a single fixed starting character" - i.e. a character class.

'S'帮助“没有单个固定起始字符的非锚定模式” - 即字符类。