用HIGHLIGHT.JS 可以很简单的实现代码高亮,youBBS的内容格式化是通过函数 set_content 实现,也要从这个函数入手。
首先是下载HIGHLIGHT.JS 和 自己喜欢的代码高亮CSS文件, 支持定制,勾选你的论坛经常贴的代码类型,当然没有你想要的语言也不影响,它会自动以文本格式显示高亮。
在youBBS 上实现
首先是定义一种方便的、在其它地方不常用的代码标识,我这里是使用三个“反单引号”(在键盘左上角,Esc 下面,英文输入)框住代码。其次是用正则把所有的代码提取出来并用pre code 标签框住代码,
1
<pre><code>代码</code></pre>
同时自己定义一个代码“占位符”,只要占位符在接下来的 html 格式化里不被替换掉就行。最后是把占位符替换为源代码。
上面实现思路看不懂也没关系,按下面方法来也可以实现。
具体操作
打开/common.php 找到 函数set_content 把它重命名为 set_content_rich。
新增一个函数 set_content,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function set_content($text, $spider='0'){
if(strpos(' '.$text, '```')){
preg_match_all('/```([\s\S]*?)```/', $text, $mat);
$code_arr = array();
$code_new_arr = array();
for($i=0;$i<count($mat[0]);$i++){
//youxascodetag 是你自己定义的一个代码占位符,最好不让别人知道
$code_tag_place = '[youxascodetag_'.$i.']';
$code_arr[$i] = $code_tag_place;
$code_v = trim($mat[1][$i]);
$code_v = str_replace("<", '<', $code_v);
$code_v = str_replace(">", '>', $code_v);
$code_new_arr[$i] = '<pre><code>'.$code_v.'</code></pre>';
$text = str_replace($mat[0][$i], $code_tag_place, $text);
}
$text = set_content_rich($text, $spider);
foreach($code_arr as $k=>$v){
$text = str_replace($v, $code_new_arr[$k], $text);
}
$text = str_replace("<p><pre>", '<pre>', $text);
$text = str_replace("</pre></p>", '</pre>', $text);
return $text;
}
return set_content_rich($text, $spider);
}
顺便对set_content_rich 作点小修改
1
2
3
4
5
// 添加这两行
$text = str_replace("\r\n", '</p><p>', $text);
$text = str_replace("<p></p>", '', $text);
return $text;
在两个模板文件引入相关js、ccs: layout.php、ios_layout.php
1
2
3
<link rel="stylesheet" href="/static/highligt/sunburst.min.css">
<script src="/static/highligt/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
修改冲突的class: title、tag
title: 把所有模板文件(/templates/default 下)的 class="title" 改为class="nav-title",同时把网站的css 文件里的.title 改为.nav-title。
tag: 只有两个模板文件引用 ios_postpage.php,postpage.php 把class="tag",改为class="mytag",在网站的css 文件里也改为同名。
完成。可能会有bug,有问题请到 youBBS论坛 回复
ToDo
上面的方法就限制了```在文本里不能滥用,本来想识别两种方式,优先识别`{3}\n(.+?)\n`{3},再识别`{3}(.+?)`{3} 这样的格式,因为不同人的习惯可能不同,在python 里很轻易的实现并正确识别了,你可以看到上面的代码高亮里有```,在php 里识别不了。如果你实现了别忘了跟大家分享一下。