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