Welcome 微信登录

首页 / 网页编程 / PHP / PHP中替换换行符的几种方法小结

第一种:
复制代码 代码如下:
<?php
?$str="this is a test ";
$patten = array(" ", " ", " ");
?//先替换掉 ,然后是否存在 ,最后替换
$str=str_replace($order, "", $str);
?>

//php 有三种方法来解决

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

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

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

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

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

第二种实例说明:

发现一个有趣的事情:

$text="aaaa


ccc";

$text=str_replace(" ‘,"",$text);
$text=str_replace(" ‘,"",$text);
$text=str_replace(" ‘,"",$text);

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

但是事实上却是不可以!

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

最后改成这样
复制代码 代码如下:
$text=str_replace(" ","",$text);
$text=str_replace(" ","",$text);
$text=str_replace(" ","",$text);

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

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

最后写成一句话
复制代码 代码如下:
$order = array(" ", " ", " ");
$replace = "";
$text=str_replace($order, $replace, $text);

这样即可替换换行符!