Log in

View Full Version : Formatting blocks of text from MySQL database



jc_gmk
04-09-2008, 03:35 PM
I am creating a database with various products in.
One of the fields will be a desciption field.

Most of the text needs line breaks in.
Do I edit the text to include <br />'s before i enter it into the database? or is there some kind of PHP function that will include line breaks after it's called.

How would this post look in a database? Would you see all the <br />'s?

thetestingsite
04-09-2008, 03:38 PM
You could use nl2br (http://php.net/nl2br) before posting to the db (this would convert any newlines in the textarea into <br /> tags before inserting into the db).

Example:

Text like this:


This is
a
test


will be converted to something like this in the db.



This is<br />
a<br />
test


Hope this helps.

jc_gmk
04-09-2008, 03:43 PM
Thanks, i'll give that a go.

Jas
04-09-2008, 07:40 PM
If you need the text to be formatted properly (i.e. if you have a w3c validated page) a preg_replace would work better. If not, the nl2br is a lot easier to use.

$text = preg_replace("/(.*)\n/U","<p>$1</p>",$text."\n");
#the ."\n" ensures the last line is matched --------^
I think that is the correct regular expression. Anyway, that would put each line in between paragraph tags, making it valid HTML/XHTML.