代码高亮显示转义字符解决办法

  • 2019-03-01 15:17:35
  • 2,280 次阅读
  • 稿源:天马行空

前一篇文章中,在wordpress默认的后台编辑器中,添加了一个高亮代码显示按钮之后,可以在后台文本区域中贴一些纯js,php,html等代码,而能够正常显示高亮的代码。但还有不能正常显示的两个情况。

第一,代码混合

每当在文本区域贴入混合代码,就不能完全正常显示了,比如php和html代码混合,html代码就显示不出来了,只有php代码了,显示结果如下图:

error_show

第二,文本按钮切换到可视化

当在文本区域贴入代码,点击预览查看显示情况正常,但切入到可视化,再预览时,又不能正常显示了。
以上情况是代码转义而造成了,为了阻止代码转义,可以在functions加入以下代码:

a.强制阻止代码转义

function star_esc_html($content) {
    $regex = '/(<pre\s+[^>]*?class\s*?=\s*?[",\'].*?prettyprint.*?[",\'].*?>)(.*?)(<\/pre>)/sim';
    return preg_replace_callback($regex, star_esc_callback, $content);
}
function star_esc_callback($matches) {
    $tag_open = $matches[1];
    $content = $matches[2];
    $tag_close = $matches[3];
    $content = esc_html($content);
    return $tag_open . $content . $tag_close;
}
add_filter('the_content', 'star_esc_html', 2);
add_filter('comment_text', 'star_esc_html', 2);

b.强制兼容pres标签

function star_prettify_replace($text){
$replace = array( '<pres>' => '<pres class="prettyprint" >' );
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter('the_content', 'star_prettify_replace');
喜欢 3

文章评论 (0)

表情

大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头