How can I replace newline or \r\n with <br/>?
Asked Answered
W

10

94

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?

Wharve answered 10/5, 2011 at 6:34 Comment(3)
Why do you have bare \r linebreaks? AFAIK even MacOSX switched to \n.Filiation
They're coming from a client's CSV.Wharve
possible duplicate of How to remove line breaks (no characters!) from the string?Bennink
P
149

There is already the nl2br() function that 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.

Pugliese answered 10/5, 2011 at 6:35 Comment(5)
Look closer, he the OP specifically shows that they attempted to use nl2br and that it didn't work.Revolutionize
Just tried to run nl2br on a string with double carriage returns, and it worked fine.Freehanded
Look at my edit @ThomasMcCabe. I've added some (maybe) useful info.Pugliese
Please note that nl2br does NOT REPLACE but instead INSERTS before newlines, which LEAVES the nl characters and ADDS br before them.Bellbottoms
but if we have a file with line breaks and we want to read it by a php script and interpret those break lines , how to do it ?Kao
W
74

Try using this:

$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description);
Wilsey answered 10/5, 2011 at 6:53 Comment(2)
a faster alternative could be $description = str_replace(["\r\n", "\r", "\n"], "<br/>", $description) taken from this answerFactorize
(One could also use just /\R/ for all CR/LF linebreak combinations.)Equip
P
19

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);
Peculiarity answered 10/5, 2011 at 7:12 Comment(1)
nl2br is nice but this actually works (for my json stuff), thanks!Amazement
H
10

Try this:

echo str_replace(array('\r\n', '\n\r', '\n', '\r'), '<br>', $description);
Hrutkay answered 7/3, 2017 at 13:28 Comment(3)
Read about PHP strings. '\r\n' is not the same as "\r\n".Steere
Thanks @axiac, I dont have time to test, But you mean It should be something like "\r\n" right ?Hrutkay
This code-only answer is misleading to naive researchers.Weaner
B
6

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');
Bouncing answered 10/5, 2011 at 6:49 Comment(0)
Y
6

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

This works:

$description = nl2br("$description");

This doesn't work:

$description = nl2br($description);
Yeager answered 28/10, 2015 at 23:36 Comment(1)
What is the explanation?Laynelayney
O
3

This will work for sure:

str_replace("\\r", "<br />", $description); 
str_replace("\\n", "<br />", $description); 
Oaf answered 13/9, 2012 at 23:40 Comment(2)
Absolutely incorrect suggestion. "foo\\r\\nbar" will become "foobar" instead of "foo<br/>bar". Prior to replace html renders "foo bar".Strikebound
Meh. Works for some specific cases where the input is of a known format.Tajuanatak
P
2
$description = nl2br(stripcslashes($description));
Pellmell answered 30/11, 2018 at 0:9 Comment(2)
The explanation is missing from this answer.Weaner
The answer from @Pellmell allows to replace the string from a query, for example:<br> $description = nl2br(stripcslashes($row["description"]));<br> stripcslashes returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.Osteoma
B
1

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

Bowers answered 10/10, 2018 at 7:53 Comment(0)
L
-3

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 use

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

to replace unnecessary new lines by an empty string.

Lunarian answered 10/5, 2011 at 6:42 Comment(1)
\r in str_replace seems to replace everything. And furthermore, you should replace it by <br>...Floribunda

© 2022 - 2024 — McMap. All rights reserved.