Page 1 of 1

Convert crlf sequences to html tags

Posted: Thu Jan 09, 2003 8:09 am
by lovasco
dear folks,
i have built a web site with a news section, and the text of each news is fetched from a database.
the authorized user can feed the database thru a set of pages to inquiry, add, modify or delete news records.
when adding a news, he has to fill in a <textarea> with the news content.
assuming he has already written the news (notepad, ms word, others), he can copy and paste the text into the <textarea>.
the <textarea> content is then written onto the database AS IS, except stripping slashes (stripslashes($content)) and replacing each single quote with two single quotes (str_replace("'","''",$content)).
when a visitor wants to display the news, its content is read AS IS from the database and echoed (echo $content) to the browser.
obviously, special characters such as new lines or crlf sequences are not displayed properly (they should be converted into html tags, such as <br>).
assuming the text has no special formats (bold, underline, etc.) except new lines (such as NL and CRLF), my question is: how can I convert the text fetched from the database so that it is displayed properly by the browser? Text editors handle new lines in different ways (for example, notepad adds a set of ascii characters which is different from that of ms word).
thank you in advance,
luca

Posted: Thu Jan 09, 2003 9:24 am
by daven
ereg_replace("\n\r", "<br>", $content);

That should take care of new lines and carriage returns. Just make sure you have "\n\r", not "\r\n".

Posted: Thu Jan 09, 2003 9:25 am
by DaiWelsh
Usually text file line terminators ae 0x13 and/or 0x10 depending on the platform (though I think Solaris uses 0x06 or similar), so a reasonable approach might be to replace chr(13).chr(10) with <br> them Chr(13) with <br> and Chr(10) with <br>. If you are familiar with regex you should be able to do it in one step, otherwise three at most.

HTH,

Dai

Posted: Thu Jan 09, 2003 9:34 am
by twigletmac
You don't need to use str_replace() to convert new lines to HTML break tags, instead try the nl2br() function.

Mac