PHP implements a simple syntax highlighting function

Source: Internet
Author: User

A PHP implementation of a simple syntax highlighting function, Note: This function design is relatively simple, may not highlight some of the syntax, you can expand the function

  1. function Syntax_highlight ($code) {
  2. This matches--"Foobar" <--
  3. $code = Preg_replace (
  4. '/"(.*?)" /U ',
  5. ' $', $code
  6. );
  7. Hightlight functions and other structures--and function foobar () <---
  8. $code = Preg_replace (
  9. '/(\s) \b (. *?) (\b|\s) \ ()/U ',
  10. "$$",
  11. $code
  12. );
  13. Match Comments (like/* */):
  14. $code = Preg_replace (
  15. '/(\/\/) (. +) \s/',
  16. '$ A ',
  17. $code
  18. );
  19. $code = Preg_replace (
  20. '/(\/\*.*?\*\/)/s ',
  21. '$ A ',
  22. $code
  23. );
  24. Hightlight Braces:
  25. $code = Preg_replace ('/(\ (|\[|\{|\}|\]|\) |\->)/', '$ ', $code);
  26. Hightlight variables $foobar
  27. $code = Preg_replace (
  28. '/(\$[a-za-z0-9_]+)/', '$ ', $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. '$ $ ', $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 '
    ';
  60. Print syntax_highlight ($example _php_code);
  61. print '
  62. ';
  63. /*example-end*/
Copy Code
Php
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.