0

I have a string stored in a database like hello, \r\n how are you? \r\n. I want to print this string in textarea to edit the text. Which is the appropriate method to print new line in textarea instead of \r\n ? I have tried nl2br(str_replace('\r\n', '\n', $str)); but it will print \n as it is. I got my result by using

<?php echo str_replace ('\\', '' ,str_replace('<br />', PHP_EOL, str_replace('\r\n', '<br />', $str))); } ?>

Another solution I got from here is

str_replace('\r\n', '&#10;', $str);

But can anyone tell me what is &#10;. It seems HTML Entity Number. But I don't know what is it actually.

Is there any better way to do this?

softech
  • 356
  • 1
  • 4
  • 23
  • 1
    Possible duplicate of [How to replace \r & \n with
    ?](https://stackoverflow.com/questions/5946114/how-to-replace-r-n-with-br)
    – Cemal Feb 22 '18 at 09:53
  • `nl2br(str_replace('\r\n', "\n", $str));` ... or just `str_replace('\r\n', '
    ', $str));` maybe? Assuming you have quite literally got the character sequence `\r\n` in the database...
    – CD001 Feb 22 '18 at 09:58
  • Read about PHP [strings](http://php.net/manual/en/language.types.string.php). [`'\r\n'`](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single) is not the same as [`"\r\n"`](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double). – axiac Feb 22 '18 at 10:04
  • @CD001 have you tried the change you suggest? It doesn't work. – axiac Feb 22 '18 at 10:04
  • @axiac - depends on what's coming out of the database. I did specify assuming it's literally the character sequence `\r\n` (rather than `CRLF`) – CD001 Feb 22 '18 at 10:15
  • @CD001 that solution is not working for me. what I get in textarea is `hello,
    how are you?
    ` .
    – softech Feb 22 '18 at 10:35
  • Ah - so you *do* literally have `\r\n` coming from the database then... in which case it should probably be something like `` (I thought `textarea` parsed html tags for some reason...) – CD001 Feb 22 '18 at 10:42
  • `str_replace('\r\n', ' ', $str);` this is also working. But can anyone tell me what is ` ` . It seems ` HTML Entity Number`. But I don't know what is it actually. – softech Feb 22 '18 at 10:50
  • @CD001 `str_replace('\r\n', "\r\n", $str);` is worked. can you please explain more why `nl2br(str_replace('\r\n', "\n", $str));` did not worked? – softech Feb 22 '18 at 10:55
  • 1
    ` ` is the HTML entity code for the *line feed* character (ASCII 10); so that would be `"\n"` in a PHP string (note, not `'\n'` the quote types for PHP strings are important)... as for `nl2br(str_replace('\r\n', "\n", $str));` that should work **but** would insert `
    ` tags before each new line.
    – CD001 Feb 22 '18 at 11:03
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165706/discussion-between-softech-and-cd001). – softech Feb 23 '18 at 09:18

0 Answers0