我得到$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,只删除单个空格。有人能告诉我怎么做吗?


当前回答

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

其他回答

我使用以下代码和模式:

preg_replace('/\\s+/', ' ',$data)

$data = 'This is   a Text 
   and so on         Text text on multiple lines and with        whitespaces';
$data= preg_replace('/\\s+/', ' ',$data);
echo $data;

您可以在http://writecodeonline.com/php/上进行测试

说实话,如果你想要这样的东西

preg_replace('/\n+|\t+|\s+/',' ',$string);

没有preg_replace,在loop的帮助下。

<?php

$str = "This is   a Text  and so on      Text text.";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
    if (isset($str_arr[$i + 1])
       && $str_arr[$i] == ' '
       && $str_arr[$i] == $str_arr[$i + 1]) {
       unset($str_arr[$i]);
    } 
    else {
      continue;
    }
}

 echo implode("", $str_arr) ; 

 ?>

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

preg_replace("/\s{2,}/", "\t", $string);
preg_replace('/[\s]+/mu', ' ', $var);

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