Re: PHP Tips and Tricks Line breaks
People want to know how they can 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 <br /> tags on display. That's all good, except for one problem with nl2br(): it doesn't seem to convert \r newlines (edit: this has now been 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. However, if you get text from a Mac, nl2br() will not convert its newlines (again, fixed in PHP 4.2.0). To remedy this, I use 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);
__________________ Thanks & Regards
Sabari... |