我得到$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/上进行测试

<?php
#This should help some newbies
# REGEX NOTES FROM DANUEL
# I wrote these functions for my own php framework
# Feel Free to make it better
# If it gets more complicated than this. You need to do more software engineering/logic.
# (.)  // capture any character
# \1   // if it is followed by itself
# +    // one or more

class whitespace{

    static function remove_doublewhitespace($s = null){
           return  $ret = preg_replace('/([\s])\1+/', ' ', $s);
    }

    static function remove_whitespace($s = null){
           return $ret = preg_replace('/[\s]+/', '', $s );
    }

    static function remove_whitespace_feed( $s = null){
           return $ret = preg_replace('/[\t\n\r\0\x0B]/', '', $s);
    }

    static function smart_clean($s = null){
           return $ret = trim( self::remove_doublewhitespace( self::remove_whitespace_feed($s) ) );
    }
}
$string = " Hey   yo, what's \t\n\tthe sc\r\nen\n\tario! \n";
echo whitespace::smart_clean($string);
$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);

你需要:

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

您正在使用的\s\s+表示空格(空格、制表符或换行符)后面跟着一个或多个空格。这实际上意味着用一个空格替换两个或多个空格。

你想要的是用单个空格替换一个或多个空格,所以你可以使用模式\s\s*或\s+(推荐)

这是我要用的:

a.确保使用双引号,例如:

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

b.删除多余的空白,使用:

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

它可能不是最快的解决方案,但我认为它需要最少的代码,而且应该可以工作。不过,我从未使用过mysql,所以我可能是错的。