BBCode, Syntax Highlighting and more

To make the blog even easier to use, I thought I'd get away from using HTML in my entries altogether. I also wanted a way to easily paste code and have it highlighted. Since there are really only a handful of tags I needed (links, images, basic text formatting, and code), I was able to write my own parser for bbcodes, as well as a cool way of highlighting code within my posts. It also works on nested tags!

Check it out:

<?php
    function bbCode ($text) {

        // regular expressions to match bbcode tags:
        $searches = array('#\[i\](.+)\[\/i\]#siU',
                          '#\[b\](.+)\[\/b\]#siU',
                          '#\[u\](.+)\[\/u\]#siU',
                          '#\[url\s*=\s*((https?://)?[^\s]+)\](.*)\[/url\]#siU',
                          '#\[lurl\s*=\s*((https?://)?[^\s]+)\](.*)\[/lurl\]#siU',
                          '#\[url\](.*)\[/url\]#siU',
                          '#\[img\s+width\s*=\s*([\d]+)\](.*)\[/img\]#siU',
                          '#\[img\](.*)\[/img\]#siU',
                          '#\n#');

        // replacements to make
        $replaces = array('<em>$1</em>',
                          '<strong>$1</strong>',
                          '<u>$1</u>',
                          '<a href="$1" target="_blank">$3</a>',
                          '<a href="$1">$3</a>',
                          '<a href="$1" target="_blank">$1</a>',
                          '<img src="$2" style="width: $1px;" />',
                          '<img src="$1" />',
                          '<br />');

        $text = preg_replace($searches, $replaces, $text);

        return $text;

    }

    function highlightCode ($text) {

        // combine regular expression replace with php's internal highlighter
        $code = preg_replace_callback('#\[code\](.+)\[\/code\]#siU', "highlightCodeCallback", $text);

        return $code;

    }

    function highlightCodeCallback ($matches) {

        return highlight_string($matches[1], true);

    }

?>

Using parentheses instead of square brackets, here are the valid formats of tags:

Now all my blog entries are stored as plain text with no HTML markup, and it's super easy to highlight my code. Here's how I display the entry on the front-end:

echo bbCode(highlightCode($_b->content));

Comments (0)

Commenting has been disabled for this entry

If you'd like to discuss an aspect of this post, feel free to contact me via email.