将具有换行符的字符串转换为单行,换行符仍然完整

时间:2015-02-03 16:40:18

标签: php html string

我有以下字符串:

Hello Eric,

Thank you very much for the links. This was exactly what I needed.

Greetings,
John

我正在使用php的nl2br函数将新行转换为正常工作的换行符。在我的字符串上运行nl2br函数后,它变为:

Hello Eric,<br />

Thank you very much for the links. This was exactly what I needed.<br />

Greetings,<br />
John

到目前为止,这正是我想要实现的目标。但是,我现在需要将包含换行符的新字符串转换为单行,如下所示:

Hello Eric,<br />Thank you very much for the links. This was exactly what I needed.<br />Greetings,<br />John

我尝试过几种不同的方法,但似乎都没有。以下是我尝试过的一些事情:

$str = str_replace(array("\r","\n"),"",$str);

$str = str_replace(array("\r\n", "\n", "\r"), "", $str);

$str = preg_replace( "/\r|\n/", "", $str);

但这些都不适合我。

1 个答案:

答案 0 :(得分:1)

试试这个:

$str = str_replace(array("\r\n","\n"),"",$str);

而不是

$str = str_replace(array("\r","\n"),"",$str);

可以观看: http://sandbox.onlinephpfunctions.com/code/41a6fbd2c937418fce927b31f6ab74ad30f8b4d0

在此处阅读有关换行符的更多信息:    http://en.wikipedia.org/wiki/Newline#Representations