SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    $books++ == true matsko's Avatar
    Join Date
    Sep 2004
    Location
    Toronto
    Posts
    795
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular Expression Help: TAG Conversion

    I created my own TAGGING system for my form which allows for users to enter a selection of TAGS for styling text within a web textarea.

    [ B ] Bold [/ B ] = Bold <--------- ignore the spaces

    The tags get converted to their html values with the following regular expression:

    PHP Code:

    $tag 
    $tags[$i];

    $text preg_replace('#\[('.$tag.')\](.*)\[\/'.$tag.'\]#i','<span class="tag-$1">$2</span>',$text); 
    (It works the same way that it works on this forum)

    Now the converted text is stored as html into a database and then fetched each time the page is loaded. This avoids having to run the regular expression replace each time. Any actual HTML that is entered into the form, before put into the database, is filtered using htmlspecialchars() with ENT_QUOTES.

    Now when the a user needs to edit their post, the converted HTML needs to be converted back to the form TAG code.

    I use this expression for ALL the tags.

    PHP Code:

    $text 
    preg_replace('#<span class="tag-(\w+)">(.+)<\/span>#','[$1]$2[/$1]',$text); 
    I end up getting faulty results because the ending </span> html tag is the same for different form tags (such as [B] and [I]).

    So when the data is converted back to HTML I end up with results like:

    [ B ]<span class="tag-i">text[/ B ]</span>


    What should I do to avoid this. I only option I can think of is using regular "deprecated" HTML tags.
    I can't believe I ate the whole thing

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,578
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Store the text with tags in the database. Do the replacement at display time. Running the regular expression doesn't even take a whole millisecond, you get to change the HTML output at any time, this problem gets solved, and your HTML doesn't get mixed up with the user's HTML.

  3. #3
    SitePoint Evangelist praetor's Avatar
    Join Date
    Aug 2005
    Posts
    479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Better yet, have a 'compiled' field in your table that contains the processed text. If you do a lot of replacements (and in time with added features probably you'll do) it will save you some time.


Bookmarks

Posting Permissions

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