-
-
Save arcanisgk/531fbd04b2139aa82a3cd1e4250b2c58 to your computer and use it in GitHub Desktop.
Quick PHP code highlighter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function highlight_string_ex($string) { | |
static $COLORS = [ | |
"comment" => "\e[32m%s\e[0m", // green | |
"constant" => "\e[93m%s\e[0m", // yellow | |
"function" => "\e[97m%s\e[0m", // white | |
"keyword" => "\e[94m%s\e[0m", // blue | |
"magic" => "\e[93m%s\e[0m", // yellow | |
"string" => "\e[95m%s\e[0m", // magenta | |
"tag" => "\e[94m%s\e[0m", // blue | |
"variable" => "\e[36m%s\e[0m", // cyan | |
"" => "%s", | |
]; | |
static $TOKENS = [ | |
T_AS => "as", | |
T_CLOSE_TAG => "tag", | |
T_COMMENT => "comment", | |
T_CONCAT_EQUAL => "", | |
T_CONSTANT_ENCAPSED_STRING => "string", | |
T_CONTINUE => "keyword", | |
T_DOUBLE_ARROW => "", | |
T_ECHO => "keyword", | |
T_ELSE => "keyword", | |
T_FILE => "magic", | |
T_FOREACH => "keyword", | |
T_FUNCTION => "keyword", | |
T_IF => "keyword", | |
T_IS_EQUAL => "", | |
T_ISSET => "keyword", | |
T_LIST => "keyword", | |
T_OPEN_TAG => "tag", | |
T_RETURN => "keyword", | |
T_STATIC => "keyword", | |
T_VARIABLE => "variable", | |
T_WHITESPACE => "", | |
]; | |
$output = ""; | |
foreach (token_get_all($string) as $token) { | |
if (is_string($token)) { | |
// plain string | |
$output .= $token; | |
continue; | |
} | |
list($t, $str) = $token; | |
if ($t == T_STRING) { | |
// T_STRING represents constants and other names | |
if (function_exists($str)) { | |
$output .= sprintf($COLORS["function"], $str); | |
} else if (defined($str)) { | |
$output .= sprintf($COLORS["constant"], $str); | |
} else { | |
$output .= $str; | |
} | |
} else if (isset($TOKENS[$t])) { | |
$output .= sprintf($COLORS[$TOKENS[$t]], $str); | |
} else { | |
// $output .= $str; | |
$output .= sprintf("<%s '%s'>", token_name($t), $str); | |
} | |
} | |
return $output; | |
} | |
echo highlight_string_ex(file_get_contents(__FILE__)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment