C++ syntax highlight with Regular Expressions
Posted on 2006-04-16
I want to colorize a C++ code by highlighting keywords in blue before outputting it inside HTML page. The problem is that if two keywords are one just after another, the followed word is not colorized (ex: in "const int i = 0;" just "const" will be in blue). So what I must do to show to the preg_replace to return to one character back after a match ?
The code I use is :
$delimiters = "\\r|\\n|\\t|\\x20|\\x21|\\x25|\\x40|\\x7E|\\x21|\\x22|\\x25|\\x26|\\x27|\\x28|\\x29|\\x2A|\\x2B|\\x2C|\\x2D|\\x2E|\\x2F|\\x3A|\\x3B|\\x3C|\\x3D|\\x3E|\\x3F|\\x40|\\x5B|\\x5C|\\x5D|\\x5E|\\x7B|\\x7C|\\x7D|\\x7E";
$from = "\"(" . $delimiters . ")(auto|int|bool|short|long|void|...|#ifndef|#undef)(" . $delimiters . ")\"";
$to = "$1<font color=blue>$2</font>$3";
$new_code = preg_replace($from, $to, $new_code);