首頁 >後端開發 >php教程 >php實作簡單的語法高亮函數

php實作簡單的語法高亮函數

WBOY
WBOY原創
2016-07-25 08:43:111210瀏覽

一个php实现的简单语法高亮显示的函数,注意:这个函数设计的比较简单,可能对某些语法不能高亮显示,你可以自己扩充该函数的功能

  1. function syntax_highlight($code){
  2. // this matches --> "foobar" <--
  3. $code = preg_replace(
  4. '/"(.*?)"/U',
  5. '""', $code
  6. );
  7. // hightlight functions and other structures like --> 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. '
    ',
  17. $code
  18. );
  19. $code = preg_replace(
  20. '/(/*.*?*/)/s',
  21. '
',
  • $code
  • );
  • // hightlight braces:
  • $code = preg_replace('/((|[|{|}|]|)|->)/', '', $code);
  • // hightlight variables $foobar
  • $code = preg_replace(
  • '/($[a-zA-Z0-9_] )/', '', $code
  • );
  • /* The b in the pattern indicates a word boundary, so only the distinct
  • ** word "web" is matched, and not a word partial like "webbing" or "cobweb"
  • */
  • // special words and functions
  • $code = preg_replace(
  • '/b(print|echo|new|function)b/',
  • '', $code
  • );
  • return $code;
  • }
  • /*example-start*/
  • /*
  • ** Create some example PHP code:
  • */
  • $example_php_code = '
  • // some code comment:
  • $example = "foobar";
  • print $_SERVER["REMOTE_ADDR"];
  • $array = array(1, 2, 3, 4, 5);
  • function example_function($str) {
  • // reverse string
  • echo strrev($obj);
  • }
  • print example_function("foo");
  • /*
  • ** A multiple line comment
  • */
  • print "Something: " . $example;';
  • // output the formatted code:
  • print '
    ';</li>
    <li>print syntax_highlight($example_php_code);</li>
    <li>print '
    ';
  • /*example-end*/
  • 复制代码
    php


    陳述:
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn