7

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

sharmacal
  • 457
  • 1
  • 6
  • 25
  • You can fix this with Javascript. \r and \n are not plain HTML like
    . Take a look at this: http://stackoverflow.com/questions/863779/textarea-line-breaks-javascript
    – Kevinvhengst Oct 24 '13 at 13:48
  • possible duplication of http://stackoverflow.com/questions/3059091/how-to-remove-carriage-returns-from-output-of-string – Yatin Trivedi Oct 24 '13 at 13:48

7 Answers7

11

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.

andromeda
  • 4,433
  • 5
  • 32
  • 42
  • 2
    `stripcslashes` works well when outputting data back into the textarea and `nl2br` works for regular html output. Thanks for your answer. – Whip Jul 04 '18 at 09:36
4

I hope str_replace saves you.

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

OUTPUT:

lin1
lin2
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
4

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.

Ian
  • 101
  • 1
  • 8
4
<?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.

Tahir Afridi
  • 190
  • 3
  • 14
1

you overdo quote in insert/update statement

This problem in you case you can solve doing next

<?php
$str = 'lin1\r\nlin2';
$solved_str = str_replace(array("\\r","\\n"), array("\r","\n"), $str);

var_dump($str,$solved_str);

But you need to check insert/update statement on over quotation escape symbols

dododo
  • 256
  • 1
  • 6
1

I would recommend using double quotes for \r\n such as "\r\n". I've never had it work properly with single quotes.

blinkums
  • 56
  • 3
1

For non- textarea use this function

function escapeNonTextarea($string){

    $string=str_replace(array('\n','\r\n','\r'),array("<br>","<br","<br>"),$string);
    return $string;
}

For text area use this function

function escapeTextarea($string){

    $string=str_replace(array('\n','\r\n','\r'),array("\n","\r\n","\r"),$string);

    return $string;
}

call appropriate function and pass argument

boonu
  • 339
  • 2
  • 5