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

我整理了几个比较适合的实例了,对于它们我们是有很多站长都测试过并用过了,不过文章最后我的总结也是生重要的哦,至于原因我也说不上了,因为chr是ascii编码了所以有时浏览器会自动转成ascii,特别像ff浏览器就是这样的。

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

代码如下复制代码

<?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使换行变成<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)这样才可以替换的哦。