您可以像這樣變更高亮顯示的色彩
<?php
ini_set("highlight.comment", "#008000");
ini_set("highlight.default", "#000000");
ini_set("highlight.html", "#808080");
ini_set("highlight.keyword", "#0000BB; font-weight: bold");
ini_set("highlight.string", "#DD0000");
?>
如您在上面的範例中所見,您甚至可以新增額外的樣式,例如粗體文字,因為這些值會直接設定到 DOM 屬性 "style"。
此外,此函式僅在高亮顯示以 "<?php" 前綴開頭的文字。但是此函式也可以高亮顯示其他類似的格式 (不是完美,但總比沒有好),例如 HTML、XML、C++、JavaScript 等。我使用以下函式來高亮顯示不同的檔案類型,效果還不錯
<?php
function highlightText($text)
{
$text = trim($text);
$text = highlight_string("<?php " . $text, true); $text = trim($text);
$text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1); $text = preg_replace("|\\</code\\>\$|", "", $text, 1); $text = trim($text); $text = preg_replace("|\\</span\\>\$|", "", $text, 1); $text = trim($text); $text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(<\\?php )(.*?)(\\</span\\>)|", "\$1\$3\$4", $text); return $text;
}
?>
請注意,它也會移除 <code> 標籤,因此您可以直接取得格式化的文字,這讓您有更大的自由來處理結果。
我個人建議結合這兩件事,以便為具有不同高亮顯示色彩組的不同檔案類型提供良好的高亮顯示函式
<?php
function highlightText($text, $fileExt="")
{
if ($fileExt == "php")
{
ini_set("highlight.comment", "#008000");
ini_set("highlight.default", "#000000");
ini_set("highlight.html", "#808080");
ini_set("highlight.keyword", "#0000BB; font-weight: bold");
ini_set("highlight.string", "#DD0000");
}
else if ($fileExt == "html")
{
ini_set("highlight.comment", "green");
ini_set("highlight.default", "#CC0000");
ini_set("highlight.html", "#000000");
ini_set("highlight.keyword", "black; font-weight: bold");
ini_set("highlight.string", "#0000FF");
}
$text = trim($text);
$text = highlight_string("<?php " . $text, true); $text = trim($text);
$text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1); $text = preg_replace("|\\</code\\>\$|", "", $text, 1); $text = trim($text); $text = preg_replace("|\\</span\\>\$|", "", $text, 1); $text = trim($text); $text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(<\\?php )(.*?)(\\</span\\>)|", "\$1\$3\$4", $text); return $text;
}
?>