欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2024-04-06 11:19:43
...

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

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

php