php实现简单的语法高亮函数实例分析

本文实例讲述了php实现简单的语法高亮函数,分享给大家供大家参考,具体分析如下:

这是一个php实现的简单语法高亮显示的函数,注意:这个函数设计的比较简单,可能对某些语法不能高亮显示,你可以自己扩充该函数的功能

  1. function syntax_highlight($code){
  2. // this matches --> "foobar" <--
  3. $code = preg_replace(
  4. '/"(.*?)"/U',
  5. '&quot;<span >$1</span>&quot;', $code
  6. );
  7. // hightlight functions and other structures like --> function foobar() <---
  8. $code = preg_replace(
  9. '/(\s)\b(.*?)((\b|\s)\()/U',
  10. '$1<span >$2</span>$3',
  11. $code
  12. );
  13. // Match comments (like /* */):
  14. $code = preg_replace(
  15. '/(\/\/)(.+)\s/',
  16. '<span ><i>$0</i></span>',
  17. $code
  18. );
  19. $code = preg_replace(
  20. '/(\/\*.*?\*\/)/s',
  21. '<span ><i>$0</i></span>',
  22. $code
  23. );
  24. // hightlight braces:
  25. $code = preg_replace('/(\(|\[|\{|\}|\]|\)|\->)/', '<strong>$1</strong>', $code);
  26. // hightlight variables $foobar
  27. $code = preg_replace(
  28. '/(\$[a-zA-Z0-9_]+)/', '<span >$1</span>', $code
  29. );
  30. /* The \b in the pattern indicates a word boundary, so only the distinct
  31. ** word "web" is matched, and not a word partial like "webbing" or "cobweb"
  32. */
  33. // special words and functions
  34. $code = preg_replace(
  35. '/\b(print|echo|new|function)\b/',
  36. '<span >$1</span>', $code
  37. );
  38. return $code;
  39. }
  40. /*example-start*/
  41. /*
  42. ** Create some example PHP code:
  43. */
  44. $example_php_code = '
  45. // some code comment:
  46. $example = "foobar";
  47. print $_SERVER["REMOTE_ADDR"];
  48. $array = array(1, 2, 3, 4, 5);
  49. function example_function($str) {
  50. // reverse string
  51. echo strrev($obj);
  52. }
  53. print example_function("foo");
  54. /*
  55. ** A multiple line comment
  56. */
  57. print "Something: " . $example;';
  58. // output the formatted code:
  59. print '<pre>';
  60. print syntax_highlight($example_php_code);
  61. print '</pre>';
  62. /*example-end*/