Results 1 to 2 of 2

Thread: How to maintain formatting in MySQL text ?

  1. #1
    Join Date
    Nov 2009
    Posts
    9

    Question How to maintain formatting in MySQL text ?

    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.

  2. #2
    Join Date
    Feb 2007
    Location
    Ireland
    Posts
    1,007
    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 - Inserts HTML line breaks before all newlines in a string
    htmlentities - Convert all applicable characters to HTML entities
    wordwrap - 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 are faster and should do the trick for basic BB codes...

    Here's a simple example:

    PHP Code:
    $myText "[b]Hello World[/b] is a piece of text commonly used to welcome a user to their first [i]working application[/i] in a new [u]computer language.[/u]";

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

    $myText str_replace($searchArr$replaceArr$myText); 
    “The best thing about a boolean is even if you are wrong, you are only off by a bit.”

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •