Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

line breaks showing up as \r\n in textarea

Tags:

html

php

I am trying to display a data into textarea which is fetched from tables that i have submitted via another form. The issue comes up when a new line is entered.

The data getting displayed in the textarea is as

lin1\r\nlin2

it should be like

lin1
lin2

I have tried nl2br but it does not work as expected. How can i make things optimized. Thanks

like image 623
sharmacal Avatar asked Oct 24 '13 13:10

sharmacal


People also ask

How do I preserve line breaks in textarea?

If you want your text to overflow the parent's boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces. Enjoy!

Does textarea support new line?

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character. Here is the HTML for the examples in this article. Copied!

How do you store line breaks in database?

Insert SQL carriage return and line feed in a string In SQL Server, we can use the CHAR function with ASCII number code. We can use the following ASCII codes in SQL Server: Char(10) – New Line / Line Break. Char(13) – Carriage Return.

How do you show line breaks in HTML?

The <br> HTML element produces a line break in text (carriage-return).


4 Answers

This problem can be solved using stripcslashes() when outputting your data.

Please note that the method above is different from stripslashes() which doesn't work in this case.

I tried using nl2br but it wasn't sufficient either.

like image 61
andromeda Avatar answered Nov 09 '22 00:11

andromeda


I hope str_replace saves you.

<?php
$str='lin1\r\nlin2';
$str=str_replace('\r\n','<br>',$str);
echo $str;

OUTPUT:

lin1
lin2
like image 44
Shankar Narayana Damodaran Avatar answered Nov 09 '22 01:11

Shankar Narayana Damodaran


This is a common question and the most common answers are ln2br or str_replace.

However this is just creating unnecessary code.

In reality the problem is pretty much always that you have run the data through a mysql escape function before displaying it. Probably while you were in the process of saving it. Instead, escape the data for saving but display an unescaped version.

like image 29
Ian Avatar answered Nov 09 '22 00:11

Ian


<?php echo str_replace('\r\n', "\r\n", $text_with_line_breaks); ?>

See single quotes & double quotes this is a trick.

A perfect solution for newbies.

like image 40
Tahir Afridi Avatar answered Nov 09 '22 00:11

Tahir Afridi