作者johnney (You make me Complete!)
看板Web_Design
標題Re: [問題]請問從MySQL裡抓文字資料如何才能分行?
時間Sat Nov 19 08:00:55 2005
最近看到的...
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). :)
PHP Code:
$txt = preg_replace('/\r\n|\r/', "\n", $txt);
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.119.170.182