Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php将多个空格替换为单个空格_Php_Regex_Formatting_String Formatting_Ereg Replace - Fatal编程技术网

php将多个空格替换为单个空格

php将多个空格替换为单个空格,php,regex,formatting,string-formatting,ereg-replace,Php,Regex,Formatting,String Formatting,Ereg Replace,我试图用一个空格替换多个空格。当我使用ereg\u replace时,我得到一个错误,它被弃用了 ereg_replace("[ \t\n\r]+", " ", $string); 有相同的替代品吗。我需要将多个“空格和多个nbsp空格替换为一个空格。使用和而不是[\t\n\r]使用\s: $output = preg_replace('!\s+!', ' ', $input); 发件人: \d、 \w和\s 速记字符类匹配 数字、文字字符(字母、, 数字和下划线),以及 空白(空格、制表符

我试图用一个空格替换多个空格。当我使用
ereg\u replace
时,我得到一个错误,它被弃用了

ereg_replace("[ \t\n\r]+", " ", $string);
有相同的替代品吗。我需要将多个
空格和多个
nbsp
空格替换为一个空格。

使用和而不是
[\t\n\r]
使用
\s

$output = preg_replace('!\s+!', ' ', $input);
发件人:

\d、 \w和\s

速记字符类匹配 数字、文字字符(字母、, 数字和下划线),以及 空白(空格、制表符和行) 休息)。可以在内部和外部使用 在字符类之外


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

@Cletus:这个空格将用空格替换单个空格。你不认为像:preg_replace(“/(?:\s+\n |\t)/”,“$x)这样的东西会更有效,特别是在有几个空格的文本上?@codaddict:碰巧,刚才我对现实生活中的数据、结果(对约8300篇不同文本文章的调用)进行了基准测试:
/(?:\s+\n |\t)/
=>1410(最慢),
/\s+/
=>611(ok'ish),
/\s\s+/
=>496(最快)。最后一个并不能取代单个的
\n
\t
,但这对我来说是可以的。/\s{2,}/u'-如果您有一些UTF-8问题,请为unicode添加/u开关有
mb_ereg_replace
@cletus,干得好!保持这个正则表达式模式,有没有办法去掉字符串左右的所有空格?例如,“abc”将是“abc”,我知道我们可以使用trim($output),但最好是在regex中使用它,而不是替换“\n”(PHP5.3),“/\s+/”完成任务。;)实际上,这有助于\s弄乱我的多字节字,用某种正方形替换Š。@MārtiņšBriedis有单独的多字节函数:与其他答案不同,此命令只替换空格(而不是换行符等),这正是我们所需要的!非常感谢你!这正是我需要的,谢谢!一条线来统治他们。
preg_replace("/[[:blank:]]+/"," ",$input)
$output = preg_replace('/\s+/', ' ',$input);