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

WBOY
發布: 2016-07-25 08:43:11
原創
1123 人瀏覽過

一个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


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!