home 首页 » 精彩博客 » 博客查看

Syntax Highlighting and Allowing html in Comments - Jay Pipes

 2008-02-28 12:40:11 

原文地址:http://jpipes.com/index.php?/archives/216-Syntax-Highlighting-and-Allowing-html-in-Comments.html

Like I said my last post, the new MySQL Forge commenting system is pretty slick. It gives commenters a lot of freedom in how they wish to display their comments, including syntax-highlighted code sections, while at the same time being security-conscious about XSS attacks and such. The htmlPurifier and GeSHi PHP libraries are used in tandem to give flexibility and security at the same time.

The code to enable this is fairly short. For you PHP devs out there, here is the code that does everything for cleaning and "codifying" the comments:

  1. /**
  2.   * Highlights the text as code in the supplied language
  3.   *
  4.   * @return string The marked up code
  5.   * @param subject The text to markup
  6.   * @param language The language to use for highlighting
  7.   */
  8. public static function syntax_highlight($subject, $language) {
  9. /* Format the code with GeSHi */
  10. include_once(APP_DIR . '/opt/geshi/geshi.php');
  11. $geshi= new GeSHi($subject, $language);
  12. $geshi->enable_classes();
  13. $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
  14. return $geshi->parse_code();
  15. }
  16.  
  17. /**
  18.   * Returns a cleaned and syntax-highlighted string of html
  19.   *
  20.   * @return string Cleaned and codified text
  21.   * @param subject The text to cut into code pieces
  22.   */
  23. public static function clean_and_codify($subject) {
  24. $original= $subject;
  25. $code_pieces= array();
  26. $code_regex= '/[\[\]code\s*(lang|language)\=[\"\'](\w+)[\"\'][\]\>]([\D\S]+?)[\[\]

Truncated by Planet PHP, read more at the original (another 12360 bytes)

收藏:

评论:共 
7
 条