我发现了这个用PHP编写的简单通用语法高亮器,在这里,并对其进行了一些修改:
<?php
class SyntaxHighlight {
public static function process($s) {
$s = htmlspecialchars($s);
$s = str_replace('\\\\','\\\\<e>', $s);
$regexp = array(
'/(
\/\*.*?\*\/|
\/\/.*?\n|
\#.[^a-fA-F0-9]+?\n|
\<\!\-\-[\s\S]+\-\-\>|
(?<!\\\)".*?(?<!\\\)"|
(?<!\\\)\'(.*?)(?<!\\\)\'
)/isex'
=> 'self::replaceId($tokens,\'$1\')',
'/([\-\!\%\^\*\(\)\+\|\~\=\`\{\}\[\]\:\"\'<>\?\,\.\/]+)/'
=> '<span class="P">$1</span>',
'/(?<!\w)(
(0x|\#)[\da-f]+|
\d+|
\d+(px|em|cm|mm|rem|s|\%)
)(?!\w)/ix'
=> '<span class="N">$1</span>',
'/(?<!\w|>|\#)(
[A-Z_0-9]{2,}
)(?!\w)/x'
=> '<span class="D">$1</span>',
'/(?<!\w|\$|\%|\@|>)(
and|or|xor|for|do|while|foreach|as|return|die|exit|if|then|else|
elseif|new|delete|try|throw|catch|finally|class|function|string|
array|object|resource|var|bool|boolean|int|integer|float|double|
real|string|array|global|const|static|public|private|protected|
published|extends|switch|true|false|null|void|this|self|struct|
char|signed|unsigned|short|long
)(?!\w|=")/ix'
=> '<span class="K">$1</span>',
'/(?<!\w)(
(\$|\%|\@)(\->|\w)+
)(?!\w)/ix'
=> '<span class="V">$1</span>'
);
$tokens = array();
$s = preg_replace(array_keys($regexp), array_values($regexp), $s);
$s = str_replace(array_keys($tokens), array_values($tokens), $s);
$s = str_replace(array('<e>', "\t"), array('', ' '), $s);
return '<pre><code>' . $s . '</code></pre>';
}
private static function replaceId(&$a, $match) {
$id = "##r" . uniqid() . "##";
if(substr($match, 0, 2) == '//' || substr($match, 0, 2) == '/*' || substr($match, 0, 2) == '##' || substr($match, 0, 7) == '<!--') {
$a[$id] = '<span class="C">' . $match . '</span>';
} else {
$a[$id] = '<span class="S">' . $match . '</span>';
}
return $id;
}
}
?>
演示: http://phpfiddle.org/lite/code/1sf-htn
更新
我刚刚创建了一个我的JavaScript通用语法高亮器的PHP版本,链接在这里 → https://github.com/taufik-nurrohman/generic-syntax-highlighter/blob/master/generic-syntax-highlighter.php
使用方法:
<?php require 'generic-syntax-highlighter.php'; ?>
<pre><code><?php echo SH('<div class="foo"></div>'); ?></code></pre>