How to replace newline or \\r\\n with <br/>?

我是研究僧i 提交于 2019-11-26 13:04:53
Robik

There is already nl2br() function that replaces inserts <br> tags before new line characters:

Example (codepad):

<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";

echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

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:

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.

afarazit

Try using this

$description = preg_replace("/\r\n|\r|\n/",'<br/>',$description);

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:

str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),"<br/>",$description);

nl2br() as you have it should work fine:

$description = nl2br($description);

It's more likely that the unclosed ' on the first line of your example code is causing your issue. Remove the ' after $description...

...$description');

nl2br() worked for me, but I needed to wrap variable with double quotes:

This works:

$description = nl2br("$description");

This doesn't work:

$description = nl2br($description);
Radeck

This will work for sure:

str_replace("\\r","<br />",$description); 
str_replace("\\n","<br />",$description); 

Try this:

echo str_replace( array('\r\n','\n\r','\n','\r'), '<br>' , $description );
$description = nl2br(stripcslashes($description));

I think str_replace(array("\r\n", "\r", "\n"), " ", $string); Will work.

Evgeniy Skulditsky

If you are using nl2br all occurrences of \n and \r will be replaced by <br>. But if (i dont know how it is) you still get new lines you can use

str_replace("\r","",$description);
str_replace("\n","",$description);

To replase unnecessary new lines by empty string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!