Using Zend Studio with Zend Framework = super fast / easy development.

BBCode PHP Syntax Highlighting For Lazy People

April 26th, 2009 by Ray in Cookbook, PHP/MySQL | Tags: , | No Comments

While working on one of my little side projects, I came across a problem where I wanted to highlight bbcode syle php tags in my text (e.g. [PHP] echo “code goes here”; [/PHP]).

Being lazy and using regex (I love it!), I came up with the following solution:

// test text w/embedded code
$text = "This is a sample text string with PHP style tags. [PHP] echo 'Hello'; [/PHP]
// and I made sure to make this case insensitive.
$pattern = "/\[PHP\](.*)\[\/PHP\]/Uis";
// the magic!
$matchCount = preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
if ($matchCount !== false && $matchCount > 0) {
    foreach ($matches as $match) {
        // highlight_string forces us to start with at least the php opening tag
        $highlightedCode = highlight_string('<?php'.$match[1].'?>', true);
        // finally, replace the original non-highlighted text with the highlighted text
        $text = preg_replace($pattern, $highlightedCode, $text, 1);
    }
}
echo $text;

Just FYI, this was a quick one-off and wasn’t intended to scale with other bbcode style tags. Also, in my real code, the [PHP] tags are lowercase. The only reason they are uppercase is because the syntax highlighter in Wordpress isn’t smart enough to distinguish the tags in my code and tags to signify syntax highlighting.


Leave a Reply