用PHP替换多余的空格和换行符?

Tei*_*eiv 35 php regex whitespace

$string = "My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs";

echo preg_replace("/\s\s+/", " ", $string);
Run Code Online (Sandbox Code Playgroud)

我阅读了PHP的文档并遵循preg_replace的教程,但是这段代码产生了

我的文字有很多空白,有很多空格和标签

我怎样才能把它变成:

我的文字有很多空白,有
很多空格和标签

Fra*_*nes 49

首先,我想指出新行可以是\ r,\n或\ r \n,具体取决于操作系统.

我的解决方案

echo preg_replace('/[ \t]+/', ' ', preg_replace('/[\r\n]+/', "\n", $string));
Run Code Online (Sandbox Code Playgroud)

如有必要,可将其分为2行:

$string = preg_replace('/[\r\n]+/', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);
Run Code Online (Sandbox Code Playgroud)

更新:

一个更好的解决方案是这个:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\n", $string));
Run Code Online (Sandbox Code Playgroud)

要么:

$string = preg_replace('/\s*$^\s*/m', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);
Run Code Online (Sandbox Code Playgroud)

我已经改变了正则表达式,使多行更好地分成一行.它采用"米"修饰符(这使得^和$开始和新线年底匹配),并删除任何\ S(空格,制表,新行,换行)字符的字符串,一开始的结束下一个.这解决了空行只有空格的问题.在前面的例子中,如果一行填充了空格,则会跳过额外的行.


小智 9

编辑了正确的答案.从PHP 5.2.4开始,以下代码将执行:

echo preg_replace('/\v(?:[\v\h]+)/', '', $string);
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说效果更好.接受的答案并没有完全删除空白的新行,而这样做并且代码更少!谢谢! (5认同)

Sou*_*rav 5

替换多个换行符、制表符、空格

$text = preg_replace("/[\r\n]+/", "\n", $text);
$text = preg_replace("/\s+/", ' ', $text);
Run Code Online (Sandbox Code Playgroud)

测试:)


Hoà*_*gtt 5

//Newline and tab space to single space

$from_mysql = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $from_mysql);


// Multiple spaces to single space ( using regular expression)

$from_mysql = ereg_replace(" {2,}", ' ',$from_mysql);

// Replaces 2 or more spaces with a single space, {2,} indicates that you are looking for 2 or more than 2 spaces in a string.
Run Code Online (Sandbox Code Playgroud)