This article mainly introduces the PHP implementation of simple syntax highlighting functions, examples of PHP through regular expressions to achieve syntax highlighting of the relevant skills, the need for friends can refer to the
This article illustrates the simple syntax highlighting function of PHP implementation. Share to everyone for your reference. The specific analysis is as follows:
This is a PHP implementation of the simple syntax highlighting function, Note: This function design is relatively simple, may not be highlighted in some syntax, you can expand the function
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61-62 |
function syntax_highlight ($code) {//This matches--> "Foobar" <--$code = Preg_ Replace ('/"(. *?)" /u ', ' "<span style=" color: #007F00 ">$1</span>", $code); Hightlight functions and other structures like--> function foobar () <---$code = preg_replace ('/(s) b (. *?) ((B|s) ()/U ', ' $1<span style= "color: #0000ff" >$2</span>$3 ", $code); Match Comments (like/* * *): $code = preg_replace ('///) (. +) s/', ' <span style= ' color: #660066; Background-color: #F FFCB1; " ><i>$0</i></span> ', $code); $code = Preg_replace ('/(/*.*?*/)/s ', ' <span style= ' color: #660066; Background-color: #FFFCB1; " ><i>$0</i></span> ', $code); Hightlight braces: $code = Preg_replace ('/(|[| {|}|]|)| ->)/', ' <strong>$1</strong> ', $code); Hightlight variables $foobar $code = preg_replace ('/($[a-za-z0-9_]+)/', ' <span style= ' color: #0000B3 ">$1</ Span> ', $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 ', ' <span style= ' color: # 7f007f ">$1</span>", $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"); * * * * * * Multiple line comment/print "something:". $example; '; Output the formatted code:print ' <pre> '; Print syntax_highlight ($example _php_code); print ' </pre> '; /*example-end*/ |
I hope this article will help you with your PHP programming.