我得到$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);

其他回答

简化为一个函数:

function removeWhiteSpace($text)
{
    $text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
    $text = preg_replace('/([\s])\1+/', ' ', $text);
    $text = trim($text);
    return $text;
}

基于丹尼尔·奥尼尔的答案。

你所需要的就是像下面这样运行它:

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

没有preg_replace ()

$str = "This is   a Text \n and so on \t     Text text.";
$str = str_replace(["\r", "\n", "\t"], " ", $str);
while (strpos($str, "  ") !== false)
{
    $str = str_replace("  ", " ", $str);
}
echo $str;

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

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