Skip to content

Instantly share code, notes, and snippets.

@arcanisgk
Forked from requinix/highlight_string_ex.php
Last active February 24, 2021 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arcanisgk/531fbd04b2139aa82a3cd1e4250b2c58 to your computer and use it in GitHub Desktop.
Save arcanisgk/531fbd04b2139aa82a3cd1e4250b2c58 to your computer and use it in GitHub Desktop.
Quick PHP code highlighter
<?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