SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Apr 2009
    0 Post(s)
    0 Thread(s)

    BBCode and RegEx

    Hello, I made a simple function to parse my BBCODE.

    I am having trouble now with the 'quote' bbcode. My problem is when There is a quote inside a quote.

    This is my quote structure: (Please note the 'Q's have been changed to 'K's or else this forum would parse the tags)

    [KUOTE=username] The Quote [/KUOTE]

    And let's say I have something like this:

    [KUOTE=username] [KUOTE=username] The Quote [/KUOTE] Another quote [/KUOTE]

    It doesn't work.

    Here part of my code:

    PHP Code:
    $bbreplace = array ('/(\[[Bb]\])(.+)(\[\/[Bb]\])/',      // Bold Regex
    '/(\[[Ii]\])(.+)(\[\/[Ii]\])/',        // Italic Regex
    '/(\[[Uu]\])(.+)(\[\/[Uu]\])/',        // Underline Regex
    '/(\[[Ii][Mm][Gg]\])(.+)(\[\/[Ii][Mm][Gg]\])/',        // Img Regex
    '/(\[[Uu][Rr][Ll]=)(.+)(\])(.+)(\[\/[Uu][Rr][Ll]\])/',        // Url Regex
    '/(\[[Qq][Uu][Oo][Tt][Ee]=)(.+)(\])(.+)(\[\/[Qq][Uu][Oo][Tt][Ee]\])/'        // Quote Regex
    $bbreplacements = array (    '<b>\\2</b>',        // Bold Replacement
    '<i>\\2</i>',        // Italic Replacement
    '<u>\\2</u>',        // Underline Replacement
    '<img src="\\2" />',        // Img Replacement
    '<a href="\\2">\\4</a>',     // Url Replacement
    '<div style="width: 95%; padding: 5px; background-color: #00384f; font-size: 11px; border: #00384f 1px solid; margin-left: 20px;"><b>Posted by \\2</b><p>\\4</p></div>'
    $message preg_replace($bbreplace$bbreplacements$message);        //Replace BBCODE 
    I am just wondering how I could go about changing the RegEx expression to take care of both quotes.

    Thanks in advance.

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    0 Post(s)
    0 Thread(s)
    The manual gives some sample code of how to recursively parse nested structures like this using a regular expression.

    I'm not sure how you plan to use your code, but be aware you have created an xss nightmare. Making a safe bbcode system is not a trivial task. There's a lot of challenges and pitfalls that you may not realize.

    ps- something else that won't currently work is
    PHP Code:
    $message '[b]bold[/b] not bold [b]bold[/b]'

  3. #3
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    8 Post(s)
    0 Thread(s)
    If you have it could always use the BBcose extension

    Or there is the PEAR class HTML_BBCodeParser

    Much better then rolling your own.
    Now for me, I would just use plain old HTML and use HTMLPurifier.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


Posting Permissions

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