GeSHi (Generic Syntax Highlighter) 是強大的代碼語法高亮庫,支援 200+ 種語言。本文介紹如何將其整合到使用 FCKeditor 的 CMS 系統中,實現前台代碼高亮展示。
<?php
require_once 'geshi/geshi.php';
$source_code = '<?php echo "Hello World"; ?>';
$geshi = new GeSHi($source_code, 'php');
// 行號顯示
$geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 5);
// 整體樣式
$geshi->set_overall_style(
'color: #000066; border: 1px solid #d0d0d0; background-color: #f0f0f0;',
true
);
// 頭部信息
$geshi->set_header_content('lzy © 2008, View php source');
$geshi->set_header_content_style(
'font-family: Verdana, Arial, sans-serif; color: #808080; font-size: 70%; font-weight: bold; background-color: #f0f0ff; border-bottom: 1px solid #d0d0d0; padding: 2px;'
);
// 底部信息
$geshi->set_footer_content('Parsed in seconds');
$geshi->set_footer_content_style(
'font-family: Verdana, Arial, sans-serif; color: #808080; font-size: 70%; font-weight: bold; background-color: #f0f0ff; border-top: 1px solid #d0d0d0; padding: 2px;'
);
// 輸出高亮 HTML
$highlighted = $geshi->parse_code();
echo $highlighted;
?>
後台編輯器(FCKeditor)無需修改,只需在內容中用標記包裹代碼:
[code]PHP 代碼內容[/code]
<?php
// 1. 回調函數處理代碼塊
function geshi_content($matches) {
$con = $matches[1]; // 獲取 [code] 內容
// 還原 HTML 實體
$con = str_replace(' ', ' ', $con);
$con = str_replace('&', '&', $con);
$con = str_replace('>', '>', $con);
$con = str_replace('<', '<', $con);
$con = str_replace('"', '"', $con);
// 去除可能殘留的 HTML 標籤
$con = strip_tags($con);
// GeSHi 高亮處理
$geshi = new GeSHi($con, 'php');
$geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 5);
$geshi->set_overall_style('color: #000066; border: 1px solid #d0d0d0; background-color: #f0f0f0;', true);
$geshi->set_header_content('lzy © 2008, View php source');
$geshi->set_header_content_style('font-family: Verdana, Arial, sans-serif; color: #808080; font-size: 70%; font-weight: bold; background-color: #f0f0ff; border-bottom: 1px solid #d0d0d0; padding: 2px;');
$geshi->set_footer_content('Parsed in seconds');
$geshi->set_footer_content_style('font-family: Verdana, Arial, sans-serif; color: #808080; font-size: 70%; font-weight: bold; background-color: #f0f0ff; border-top: 1px solid #d0d0d0; padding: 2px;');
return $geshi->parse_code();
}
// 2. 文章內容輸出時替換
$content = preg_replace_callback(
'/\[code\](.+?)\[\/code\]/s',
'geshi_content',
$content
);
echo $content;
?>
'php' 替換為 'javascript'、'css'、'sql' 等即可支持其他語言parse_code() 輸出存入數據庫或文件緩存此方案完美解決了「富文本編輯器難以集成代碼高亮」的痛點,是技術類 CMS、博客、文檔系統的理想選擇。