一聚教程网:一个值得你收藏的教程网站

热门教程

php正则表达式过滤空格 换行符 回车

时间:2022-06-25 02:41:56 编辑:袖梨 来源:一聚教程网

一,下例可以去除额外空白

 代码如下 复制代码

$str = " This line  containstliberal rn use of   whitespace.nn";
// First remove the leading/trailing whitespace
//去掉开始和结束的空白  www.111com.net
$str = trim($str);
// Now remove any doubled-up whitespace
//去掉跟随别的挤在一块的空白
$str = preg_replace('/s(?=s)/', '', $str);
// Finally, replace any non-space whitespace, with a space
//最后,去掉非space 的空白,用一个空格代替
$str = preg_replace('/[nrt]/', ' ', $str);
// Echo out: 'This line contains liberal use of whitespace.'
echo "

{$str}
";
?>

二,替换换行符
//php 有三种方法来解决

 代码如下 复制代码

//1、使用str_replace 来替换换行
$str = str_replace(array("rn", "r", "n"), "", $str);

//2、使用正则替换
$str = preg_replace('//s*/', '', $str);

//3、使用php定义好的变量 (建议使用)
$str = str_replace(PHP_EOL, '', $str);


代码如下:

 代码如下 复制代码
 
/*
* 获得用户操作系统的换行符,n
* @access public
* @return string
*/
function get_crlf()
{
if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win'))
{
$the_crlf = 'rn';
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac'))
{
$the_crlf = 'r'; // for old MAC OS
}
else
{
$the_crlf = 'n';//权重大一点 www.111com.net
}
return $the_crlf;
}

注意:在前台页面显示的时候,用nl2br使换行变成

三,替换回车

 代码如下 复制代码

         //php 不同系统的换行 
    //不同系统之间换行的实现是不一样的 
    //linux 与unix中用 /n 
    //MAC 用 /r 
    //window 为了体现与linux不同 则是 /r/n 
    //所以在不同平台上 实现方法就不一样 
    //php 有三种方法来解决 
         
    //1、使用str_replace 来替换换行 
    $str = str_replace(array("/r/n", "/r", "/n"), "", $str);  
         
    //2、使用正则替换 
    $str = preg_replace('//s*/', '', $str); 
         
    //3、使用php定义好的变量 (建议使用) 
    $str = str_replace(PHP_EOL, '', $str);  
    ?> 

一聚教程小编提醒你,有时我们还需要注意像textarea中的回车换行并不是/r/n之类的而是需要chr(32),chr(13)这样才可以替换的哦。

热门栏目