Search code examples
phptagsmatchforum

PHP Check For Matching Tags In User Submitted Content


I've been putting together my own customly made forum using PHP, and it's coming along astoundingly, but I was trying to figure out if there is a way to check for matching BBCode tags? I have my own arrays set up to replace <b> with [b] and so on, but I want to be able to make sure that the tags will be closed at some point [/b] and not continue to run off of the post and onto the rest of the page.

For example: [b]This is text will show up as [b]This is text, and [b]This is text[/b] will return on the page as <b>This is text</b>

Is there a way to do this, or is there a way in PHP/HTML to 'escape' any opened tags? IE; if no [/b] is in the post, automatically add a </b> onto the end of it.


Solution

  • this is a very simple bbcode parser for your requirement:

    function bbcode($data)
    {
        $input = array(
            '/\[b\](.*?)\[\/b\]/is',
            '/\[b\](.*?)$/',
        );
        $output = array(
            '<b>$1</b>',
            '<b>$1</b>',
        );
        return preg_replace ($input, $output, $data);;
    }
    

    some examples:

    bbcode('[b]text[/]');
    //returns <b>text</b>
    
    bbcode('[b]text');
    //returns <b>text</b>
    

    See the example running here