PHP头条
热点:

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 有三种方法来解决

 代码如下  

//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.111cn.net

return $the_crlf; 
}

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

  三,替换回车

 代码如下  

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

www.phpzy.comtrue/php/11400.htmlTechArticlephp正则表达式过滤空格 换行符 回车 一,下例可以去除额外空白 代码如下 ?php $str = This line containstliberal rn use of whitespace.nn; // First remove the leading/trailingwhitespace //去掉开始和结束的空白...

相关文章

    暂无相关文章
相关频道:

PHP之友评论

今天推荐