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

WBOY
Freigeben: 2016-07-25 08:45:32
Original
948 Leute haben es durchsucht

一个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 '
    ';
    Nach dem Login kopieren
  58. print syntax_highlight($example_php_code);
  59. print '';
  60. /*example-end*/
复制代码

php


Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!