当前位置:Gxlcms > PHP教程 > php实现简单的语法高亮函数

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

时间:2021-07-01 10:21:17 帮助过:30人阅读

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

  1. function syntax_highlight($code){
  2. // this matches --> "foobar" <--
  3. $code = preg_replace(
  4. '/"(.*?)"/U',
  5. '"$1"', $code
  6. );
  7. // hightlight functions and other structures like --> function foobar() <---
  8. $code = preg_replace(
  9. '/(\s)\b(.*?)((\b|\s)\()/U',
  10. '$1$2$3',
  11. $code
  12. );
  13. // Match comments (like /* */):
  14. $code = preg_replace(
  15. '/(\/\/)(.+)\s/',
  16. '$0',
  17. $code
  18. );
  19. $code = preg_replace(
  20. '/(\/\*.*?\*\/)/s',
  21. '$0',
  22. $code
  23. );
  24. // hightlight braces:
  25. $code = preg_replace('/(\(|\[|\{|\}|\]|\)|\->)/', '$1', $code);
  26. // hightlight variables $foobar
  27. $code = preg_replace(
  28. '/(\$[a-zA-Z0-9_]+)/', '$1', $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. '$1', $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 '
    ';
  60. print syntax_highlight($example_php_code);
  61. print '
  62. ';
  63. /*example-end*/

php

人气教程排行