27

I'm using an textarea to send text to my DB.

Screenshot of db:

enter image description here

When I'm reading from the DB it removes the line breaks, how can I keep them in $row['opmerkingen']?

enter image description here

Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23
Muiter
  • 1,470
  • 6
  • 26
  • 39
  • possible duplicate of [How to remove line breaks (no characters!) from the string?](http://stackoverflow.com/questions/10757671/how-to-remove-line-breaks-no-characters-from-the-string) – kenorb Mar 03 '15 at 00:30

3 Answers3

77

When displaying text, use nl2br() to convert newlines to <br/> tags, i.e., instead of <?php echo $row['text']; ?>, use <?php echo nl2br($row['text']); ?>.

By default, browsers display newlines as spaces, therefore they have to be converted to <br/> tags.


For those who find this useful - please consider using white-space: pre-line, suggested by Emil Vikström. I'm not a web guy anymore and easily can't verify this, but Boaz says in comments that it is supported by all modern browsers. If so, that should be preferred to using nl2br().

binaryLV
  • 9,002
  • 2
  • 40
  • 42
22

An alternative to nl2br is to make use of the CSS attribute white-space:

white-space: pre-line;
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • 2
    +1 IMHO `nl2br()` *is* the alternative. Styling and formatting should be handled by CSS only, now that [all modern browsers support the `pre-line` value of the `white-space` property](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space). – Boaz Feb 24 '14 at 12:12
8

I put as follows but not working with single quotes.

echo $row['text'].'\n';

Put the double quotes. Then worked.

<textarea rows="10" cols="62" style="white-space: pre-line;" wrap="hard">
<?php echo $row['text']."\n"; ?>
</textarea>

When we getting data it is comming with \r\n. Also use the double quotes there.

Sumith Harshan
  • 6,325
  • 2
  • 36
  • 35