Line breaks
by Sanju[ Edit ] 2010-01-29 08:52:12
Line breaks
Retain textarea line breaks in HTML. You should store text in the database in its original format (e.g. with just newlines) and then use nl2br() to convert newlines to HTML
tags on display.
One problem with nl2br(): it doesn't seem to convert \r newlines. But now it is fixed in PHP 4.2.0.
Windows uses \r\n newlines; *nix uses \n; Mac uses \r.
nl2br() works correctly on text from Windows/*nix because they contain \n. If you get text from a Mac, nl2br() will not convert its newlines (fixed in PHP 4.2.0).
The following bit of code to convert \r\n or \r to \n before inserting it into the database. It won't hurt anything and ensures that nl2br() will work on the \n only newlines on display. Also, it has the side effect of saving 1 byte in the database per newline from Windows (by storing only \n instead of \r\n).
$txt = preg_replace('/\r\n|\r/', "\n", $txt);