如何用
替换换行符或 \r\n?
我试图简单地替换一些新行,并尝试了三种不同的方法,但我没有得到任何改变:
$description = preg_replace('/\r?\n|\r/', '<br/>', $description);
$description = str_replace(array("\r\n", "\r", "\n"), "<br/>", $description);
$description = nl2br($description);
这些应该都有效,但我仍然得到换行符。它们是双的:“\r\r”。这不应该使这些失败,对吧?
I am trying to simply replace some new lines and have tried three different ways, but I don't get any change:
$description = preg_replace('/\r?\n|\r/', '<br/>', $description);
$description = str_replace(array("\r\n", "\r", "\n"), "<br/>", $description);
$description = nl2br($description);
These should all work, but I still get the newlines. They are double: "\r\r". That shouldn't make any of these fail, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
已经有
nl2br()
函数插入 < code>标签在新行字符之前:
示例 (codepad):
但如果是仍然无法正常工作,请确保文本
$desciption
用双引号引起来。这是因为与双引号字符串相比,单引号不会“扩展”转义序列,例如
\n
。引用 PHP 文档:There is already the
nl2br()
function that inserts<br>
tags before new line characters:Example (codepad):
But if it is still not working make sure the text
$desciption
is double-quoted.That's because single quotes do not 'expand' escape sequences such as
\n
comparing to double quoted strings. Quote from PHP documentation:尝试使用这个:
Try using this:
字符串中可能有真正的字符“\”(单引号字符串,如@Robik所述)。
如果您非常确定 '\r' 或 '\n' 字符串也应该被替换,我在这里讨论的不是特殊字符,而是两个字符 '\' 和 'r' 的序列,然后转义 '\ ' 在替换字符串中,它将起作用:
You may have real characters "\" in the string (the single quote strings, as said @Robik).
If you are quite sure the '\r' or '\n' strings should be replaced as well, I'm not talking of special characters here but a sequence of two chars '\' and 'r', then escape the '\' in the replace string and it will work:
试试这个:
Try this:
nl2br()
正如您所拥有的那样,它应该可以正常工作:示例代码第一行中未闭合的
'
更有可能导致您的问题。删除 $description 后的 '...nl2br()
as you have it should work fine:It's more likely that the unclosed
'
on the first line of your example code is causing your issue. Remove the ' after $description...nl2br() 对我有用,但我需要用双引号将变量括起来:
这有效:
这不起作用:
nl2br() worked for me, but I needed to wrap the variable with double quotes:
This works:
This doesn't work:
这肯定会起作用:
This will work for sure:
我认为
str_replace(array("\\r\\n", "\\r", "\\n"), " ", $string);
将会工作。I think
str_replace(array("\\r\\n", "\\r", "\\n"), " ", $string);
will work.如果您使用
nl2br
,则所有出现的\n
和\r
都将替换为
。但是,如果(我不知道是怎么回事)您仍然得到新行,您可以用空字符串替换不必要的新行。
If you are using
nl2br
, all occurrences of\n
and\r
will be replaced by<br>
. But if (I don’t know how it is) you still get new lines you can useto replace unnecessary new lines by an empty string.