Page 1 of 1

bbcode

Posted: Sat Jul 26, 2008 10:52 pm
by SidewinderX
I am working on a bbcode class, and the basic replacements ([ b ], [ i ] , ect...) are easy enough to implement:

Code: Select all

<?php
 
class BBcode
{
 
    public function parse ($text)
    {
        $bbcode = array(
                        'bold' => "(\[b\](.+?)\[\/b])is");
        $replace = array(
                        'bold' => '<strong>$1</strong>');
        $text = preg_replace($bbcode, $replace, $text);
        return $text;
    }
}
$bbcode = new BBcode();
$text = '[ b ]this text is bold[/ b ]';
echo $bbcode->parse($text);
?>

However, I am trying to add a syntax highlighter to parse [ code=xxx ] tags. For the syntax highlighting I am using GeSHi class. I figured doing the following would work:

Code: Select all

<?php
 
class BBcode
{
 
    public function parse ($text)
    {
        $text = htmlentities($text);
        $bbcode = array(
                        'bold' => "(\[b\](.+?)\[\/b])is" , 
                        'code' => "(\[code\=([a-zA-Z]*)\](.+?)\[\/code])is");
        $replace = array(
                        'bold' => '<strong>$1</strong>' ,
                        'code' => $this->formatCode('$2', '$1'));
        $text = preg_replace($bbcode, $replace, $text);
        return $text;
    }
 
    public function formatCode ($code, $type)
    {
        require_once ('geshi.php');
        $geshi = new HELPERS_GeSHi($code, $type);
        $geshi->enable_line_numbers(1);
        $code = $geshi->parse_code();
        return $code;
    }
}
 
$bbcode = new BBcode();
$text = '[b]some bold text[/b]

Code: Select all

<?php echo "This is some code"; 
echo "line2";
$var = "hello world";
?>
';echo $bbcode->parse($text);?>

Now it works to an extent, but it does not highlight the syntax (and it assumes the code is one line). There is no issue with the formatCode() function. Could it be possible that the $2 and $1 are being inteperated as literals when they get passed to the formatCode() function rather than what they reference? What would you suggest as an alternative solution?

Thanks,
John

Re: bbcode

Posted: Wed Jul 30, 2008 9:32 am
by ody3307
Not sure if this will solve the problem but I see some errors in the regex.
You do not need to escape the right bracket symbol, it's not a special character.
The same applies to the equals sign; not a special character in regex.
Line 9 of the original code escapes the right bracket on the opening tag, yet does not on the closing tag (very curious).
It's possible that all these extra escape characters are messing up the regex.

Here's a resource page: http://www.regular-expressions.info/characters.html