您现在的位置是: 网站首页>文章详情 文章详情

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

Heartless Wolf 1585209011 php 1171 收藏

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

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


<?php
   $str = " This line  containstliberal rn use of   whitespace.nn";
   // First remove the leading/trailing whitespace
   //去掉开始和结束的空白  www.111cn.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 "<pre>{$str}</pre>";
?>

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

<?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);

代码如下:

<?php
   /*
   * 获得用户操作系统的换行符,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.111cn.net
       }
       return $the_crlf;
   }

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

三,替换回车

<?php
   //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)这样才可以替换的哦。

文章评论

    点击加载更多评论

我的名片

网名:Hello World

职业:PHP开发

现居:福建省-福州市

Email:565554856@qq.com

  • 图片信息

站点信息

  • 建站时间:2019-04-20
  • 文章总计:69条
  • 笔记总计:4条
  • 文章评论:0条
  • 笔记评论:0条
  • 当前访问IP:3.22.209.120