Source Code Syntax Highlighting in PHP

They said programming is an art, and syntax highlighting of source code really makes them look artistic.

I have some little scripts that I would to publish on the net, and I would like to add some colour before posting in my blog. PHP has this function show_source() that can syntax highlight a file, however it only works on PHP files. Instead of writing parsers and generators for all the programming languages known to mankind out there, I opt for something already been written - GNU Enscript.

I know that Enscript is mainly use to generate Postscript files, but in a tool which I've used before, ViewCVS, I saw how it calls Enscript to generate syntax highlighted source code listing. It then took me a few minutes to hack up a wrapper for it in PHP...

This is an demonstration of how to use it.

echo syntax_hilight('syntax_hilight.php');

Source Code

/**
 * Syntax hilighting a program source file. It calls enscript(1) to parse and
 * insert HTML tags to produce syntax hilighted version of the source. Since
 * the version of enscript I have does not support PHP hilighting, I will use
 * PHP's show_source() if the source file ends with .php.
 *
 * @param  $filename The filename of the source file to be transformed.
 * @return A text string containing syntax hilighting version of the source,
 *         in HTML.
 */
function syntax_hilight($filename) {
    if ((substr($filename, -4) == '.php')) {
        ob_start();
        show_source($filename);
        $buffer = ob_get_contents();
        ob_end_clean();
    } else {
        $argv = '-q -p - -E --language=html --color '.escapeshellcmd($filename);
        $buffer = array();

        exec("enscript $argv", $buffer);

        $buffer = join("\n", $buffer);
        $buffer = eregi_replace('^.*<PRE>',  '<pre>',  $buffer);
        $buffer = eregi_replace('</PRE>.*$', '</pre>', $buffer);
    }

    // Making it XHTML compatible.
    $buffer = eregi_replace('<FONT COLOR="', '<span style="color:', $buffer);
    $buffer = eregi_replace('</FONT>', '</style>', $buffer);

    return $buffer;
}

Updated: This has been superseded by the newer version that also can acts as a WordPress plugin.