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
- function Syntax_highlight ($code) {
- This matches--"Foobar" <--
- $code = Preg_replace (
- '/"(.*?)" /U ',
- ' $', $code
- );
- Hightlight functions and other structures--and function foobar () <---
- $code = Preg_replace (
- '/(\s) \b (. *?) (\b|\s) \ ()/U ',
- "$$",
- $code
- );
- Match Comments (like/* */):
- $code = Preg_replace (
- '/(\/\/) (. +) \s/',
- '$ A ',
- $code
- );
- $code = Preg_replace (
- '/(\/\*.*?\*\/)/s ',
- '$ A ',
- $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 '
'; - Print syntax_highlight ($example _php_code);
- print '
';
- /*example-end*/
Copy Code
|