php 语法高亮函数示例

前端之家收集整理的这篇文章主要介绍了php 语法高亮函数示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一个PHP实现的简单语法高亮显示函数,注意:这个函数设计的比较简单,可能对某些语法不能高亮显示,你可以自己扩充该函数功能PHP语法高亮函数,感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:
  1. /**
  2. * 简单语法高亮显示函数
  3. *
  4. * @param
  5. * @arrange (512.笔记) jb51.cc
  6. **/
  7. function Syntax_highlight($code){
  8. // this matches --> "foobar" <--
  9. $code = preg_replace(
  10. '/"(.*?)"/U','&quot;<span style="color: #007F00">$1</span>&quot;',$code
  11. );
  12. // hightlight functions and other structures like --> function foobar() <---
  13. $code = preg_replace(
  14. '/(\s)\b(.*?)((\b|\s)\()/U','$1<span style="color: #0000ff">$2</span>$3',$code
  15. );
  16. // Match comments (like /* */):
  17. $code = preg_replace(
  18. '/(\/\/)(.+)\s/','<span style="color: #660066; background-color: #FFFCB1;"><i>$0</i></span>',$code
  19. );
  20. $code = preg_replace(
  21. '/(\/\*.*?\*\/)/s',$code
  22. );
  23. // hightlight braces:
  24. $code = preg_replace('/(\(|\[|\{|\}|\]|\)|\->)/','<strong>$1</strong>',$code);
  25. // hightlight variables $foobar
  26. $code = preg_replace(
  27. '/(\$[a-zA-Z0-9_]+)/','<span style="color: #0000B3">$1</span>',$code
  28. );
  29. /* The \b in the pattern indicates a word boundary,so only the distinct
  30. ** word "web" is matched,and not a word partial like "webbing" or "cobweb"
  31. */
  32. // special words and functions
  33. $code = preg_replace(
  34. '/\b(print|echo|new|function)\b/','<span style="color: #7F007F">$1</span>',$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 '<pre>';
  58. print Syntax_highlight($example_PHP_code);
  59. print '</pre>';
  60. /*example-end*/
  61. /*** 代码来自编程之家 jb51.cc(jb51.cc) ***/

猜你在找的PHP相关文章