php php用一个空格替换多个空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2368539/
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 06:12:31  来源:igfitidea点击:

php Replacing multiple spaces with a single space

phpregexformattingstring-formattingereg-replace

提问by Dani

I'm trying to replace multiple spaces with a single space. When I use ereg_replace, I get an error about it being deprecated.

我正在尝试用一个空格替换多个空格。当我使用 时ereg_replace,我收到一个关于它被弃用的错误。

ereg_replace("[ \t\n\r]+", " ", $string);

Is there an identical replacement for it. I need to replace multiple " "white spaces and multiple nbspwhite spaces with a single white space.

是否有相同的替代品。我需要用一个" "空格替换多个空格和多个nbsp空格。

回答by cletus

Use preg_replace()and instead of [ \t\n\r]use \s:

使用preg_replace()和代替[ \t\n\r]使用\s

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

正则表达式基本语法参考

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

\d、\w 和 \s

匹配数字、单词字符(字母、数字和下划线)和空格(空格、制表符和换行符)的速记字符类。可以在字符类内部和外部使用。

回答by Somnath Muluk

$output = preg_replace('/\s+/', ' ',$input);

\s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

\s 是 的简写[ \t\n\r]。多个空格将替换为单个空格。

回答by ghostdog74

preg_replace("/[[:blank:]]+/"," ",$input)