Convert crlf sequences to html tags

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lovasco
Forum Newbie
Posts: 15
Joined: Fri May 17, 2002 4:25 am
Location: Milan - Italy

Convert crlf sequences to html tags

Post 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
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Post 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".
DaiWelsh
Forum Commoner
Posts: 36
Joined: Wed Jan 08, 2003 9:39 am
Location: Derbyshire, UK

Post 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
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You don't need to use str_replace() to convert new lines to HTML break tags, instead try the nl2br() function.

Mac
Post Reply