Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 

These should all work, but I still get the newlines. They are double: "\r\r". That shouldn't make any of these fail, right?

like image 838
theflowersoftime Avatar asked May 10 '11 06:05

theflowersoftime


People also ask

How do I replace all line breaks in a string with br /> elements?

The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks. The pattern /g checks across all the string occurrences.

How do you find and replace in newline?

On the keyboard, press Ctrl + H to open the Find and Replace dialog box, with the Replace tab active. On the Replace tab, click in the Find What box. On the keyboard, press Ctrl + J to enter the line break character.

How do you replace a character in a new line in Java?

Use this: text = text. replace(", ", "\n");


2 Answers

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.

like image 167
Robik Avatar answered Oct 06 '22 09:10

Robik


Try using this:

$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description); 
like image 26
afarazit Avatar answered Oct 06 '22 08:10

afarazit