当前位置:首页 > PHP教程 > PHP高级教程

PHP中替换换行符的几种方法小结

第一种:

复制代码 代码如下:

<?php
?$str="this is a test n";
$patten = array("rn", "n", "r");
?//先替换掉rn,然后是否存在n,最后替换r
$str=str_replace($order, "", $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';//权重大一点
}
return $the_crlf;
}

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

第二种实例说明:

发现一个有趣的事情:

$text="aaaa


ccc";

$text=str_replace('n‘,"",$text);
$text=str_replace('r‘,"",$text);
$text=str_replace('rn‘,"",$text);

正常来说,上面的代码应该可以替换换行符了吧

但是事实上却是不可以!

很郁闷,试了很多次,就是不起作用。

最后改成这样
复制代码 代码如下:

$text=str_replace("n","",$text);
$text=str_replace("r","",$text);
$text=str_replace("rn","",$text);

居然一切ok了~~,原来是双引号,单引号的问题!!

双引号 比单引号效率差点,因为双引号在被php解析的过程中 ,还会判断里面会不会有变量,单引号就不会有这个判断,故而一般来讲,没涉及到变量的情况下,我都会用单引号,没想到这次替换换行符,用单引号居然不行·····

最后写成一句话
复制代码 代码如下:

$order = array("rn", "n", "r");
$replace = '';
$text=str_replace($order, $replace, $text);

这样即可替换换行符!



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!