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

WBOY
풀어 주다: 2016-07-25 08:45:32
원래의
932명이 탐색했습니다.

一个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 학습자의 빠른 성장을 도와주세요!