如何用< br/>替换换行符或\ r \ n? [英] How can I replace newline or \r\n with <br/>?
问题描述
我试图简单地替换一些新行,并尝试了三种不同的方式,但是我没有任何改变:
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);
这些都应该起作用,但是我仍然可以换行.它们是双倍的:"\ r \ r".那不应该使任何这些失败,对吧?
These should all work, but I still get the newlines. They are double: "\r\r". That shouldn't make any of these fail, right?
推荐答案
已经有 nl2br()
在新行字符之前插入 <br>
标签的功能:
There is already the nl2br()
function that inserts <br>
tags before new line characters:
示例(键盘):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>
但是,如果仍然无法正常工作,请确保将文本$desciption
用双引号引起来.
But if it is still not working make sure the text $desciption
is double-quoted.
那是因为与双引号字符串相比,单引号不会扩展"诸如\n
的转义序列.引用PHP文档:
That's because single quotes do not 'expand' escape sequences such as \n
comparing to double quoted strings. Quote from PHP documentation:
注意:与双引号和Heredoc语法不同,特殊字符的变量和转义序列在单引号引起来的字符串中不会扩展.
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
这篇关于如何用< br/>替换换行符或\ r \ n?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!