PHP implements simple syntax highlighting function

WBOY
Release: 2016-07-25 08:43:11
Original
1174 people have browsed it

A simple syntax highlighting function implemented in PHP. Note: This function is relatively simple in design and may not be able to highlight certain syntaxes. You can expand the function of this function yourself

  1. function syntax_highlight($code ){
  2. // this matches --> "foobar" <--
  3. $code = preg_replace(
  4. '/"(.*?)"/U',
  5. '"$1"', $code
  6. );
  7. // highlight 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. // highlight braces:
  25. $code = preg_replace('/((|[|{|}|]|)|->)/', '$1
  26. // highlight 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 '
    ';</li>
    <li>print syntax_highlight($example_php_code);</li>
    <li>print '
    ';
  60. /*example-end*/
Copy code

php


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!