简体   繁体   English

字符串替换 <br /> 到\\ n给出了双重休息

[英]string replace <br /> to \n gives double breaks

Solution information: 方案信息:

The nl2br function does not replace \\n with <br /> as I had expected but inserts a <br /> before the \\n . nl2br函数不会像我预期的那样用<br />替换\\n但是在\\n之前插入<br />

From php.net: 来自php.net:

nl2br — Inserts HTML line breaks before all newlines in a string nl2br - 在字符串中的所有换行符之前插入HTML换行符


Original question: 原始问题:

I'm replacing <br /> elements with \\n in PHP, this is my input: 我在PHP中用\\n替换<br />元素,这是我的输入:

Top spot!<br />
<br />
123456789 123456789 123456789

This is my code: 这是我的代码:

$commenttext = str_replace("<br />", "\n", $reviewdata['comment']);

But my output is: 但我的输出是:

Top spot!



123456789 123456789 123456789

Is there something I'm missing with using str_replace? 使用str_replace有什么我想念的吗? I'm getting double the breaks returned after using it. 使用它后我得到了两倍的休息时间。

Let me show you. 让我演示给你看。 Your code before replacement: 更换前的代码:

Top spot!<br />\n<br />\n123456789 123456789 123456789

Your code after replacement: 更换后的代码:

Top spot!\n\n\n\n123456789 123456789 123456789

As you can see <br /> was correctly replaced with new line. 如您所见, <br />被新线正确替换。

Try to replace <br /> tags with the new lines first: 尝试首先用新行替换<br />标记:

$commenttext = str_replace("<br />\n", "\n", $reviewdata['comment']);
<?php

$text = 'top spot!<br />
<br />
123456789 123456789 123456789';

echo str_replace("<br />\n","\n",$text);

?>

DEMO DEMO

OUTPUT OUTPUT

top spot! 123456789 123456789 123456789

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM