我得到$row['message']从一个MySQL数据库,我需要删除所有的空白,如\n \t等。

$row['message'] = "This is   a Text \n and so on \t     Text text.";

应格式化为:

$row['message'] = 'This is a Text and so on Text text.';

我试着:

 $ro = preg_replace('/\s\s+/', ' ',$row['message']);
 echo $ro;

但它不删除\n或\t,只删除单个空格。有人能告诉我怎么做吗?


当前回答

这将用一个选项卡替换多个选项卡

preg_replace("/\s{2,}/", "\t", $string);

其他回答

<?php
$str = "This is  a string       with
spaces, tabs and newlines present";

$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);

echo $str;
echo "\n---\n";
echo "$stripped";
?>

这个输出

This is  a string   with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present

我不能在这里重复这个问题:

$x = "this    \n \t\t \n    works.";
var_dump(preg_replace('/\s\s+/', ' ', $x));
// string(11) "this works."

我不确定这是否只是一个转录错误,但在您的示例中,您使用的是单引号字符串。如果有双引号字符串,\n和\t只被当作换行符和制表符。那就是:

'\n\t' != "\n\t"

编辑:正如Codaddict指出的那样,\s\s+不会取代一个制表符。我仍然不认为使用\s+是一个有效的解决方案,所以这样如何:

preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x);
preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);

这将用一个空格替换所有制表符、换行符以及多个空格、制表符和换行符的所有组合。

$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);
preg_replace('/[\s]+/mu', ' ', $var);

\s已经包含制表符和新行,所以上面的正则表达式似乎足够了。