PDA

View Full Version : How to maintain formatting in MySQL text ?



oldsportbiker
28 Nov 2009, 12:23 AM
I'm storing short bios of employees and need to maintain some simple formatting, ( paragraphs, line breaks etc.), but when stored as Text or BLOB, PHP renders it into very plain text with no formatting. I'm looking for some PHP function that could retain the RTF formatting features. If I have to store it some other way I'm open to t, but I'd prefer to store these bios in the MySQL database rather than separate files.

Alan
28 Nov 2009, 02:10 PM
Ok, well the simple solution would be to store HTML tags in the database too... not the best way about it if your trying to maintain data neutrality.

There are a few functions that can help you:

nl2br (http://www.php.net/manual/en/function.nl2br.php) - Inserts HTML line breaks before all newlines in a string
htmlentities (http://www.php.net/manual/en/function.htmlentities.php) - Convert all applicable characters to HTML entities
wordwrap (http://www.php.net/manual/en/function.wordwrap.p) - Wraps a string to a given number of characters

There are a load of other functions that you might like.

Forums and such use BB code among the text to determine formatting. A good reason to use this approach (as opposed to using direct html tags) is that it encapsulates the implementation of the formatting, such that you can change from one formatting method to another (e.g. from html to css) without modifying the data in the database.

To implement BB code, you can use replace functions (with or without regular expressions (regex) for pattern checking). Regex is slower but more precise, while simple string replace functions such as str_replace (http://www.php.net/manual/en/function.str-replace.php) are faster and should do the trick for basic BB codes...

Here's a simple example:



$myText = "Hello World is a piece of text commonly used to welcome a user to their first working application in a new computer language.";

$searchArr = array('', '', '', '', '', '');
$replaceArr = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>');

$myText = str_replace($searchArr, $replaceArr, $myText);