-
-
Save requinix/6895f9abeb90022f729a8b58a160be60 to your computer and use it in GitHub Desktop.
<?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__)); | |
?> |
requinix
commented
Feb 24, 2021
Hello friend what would be the sequence of colors if I wanted to use
https://github.com/rdavlin/php-color-bash/blob/master/color_chart.png
https://github.com/rdavlin/php-color-bash/blob/master/bash_colors.php
when using this notation the lines are broken:
"\033[38;5;010m\033[0m"
instead of:
"\e[32m%s\e[0m"
I am looking to use a wider color palette 256 colors to create different themes.
Those strings go into sprintf, using %s placeholders to mark where the source $str should be inserted. You need to use "\033[38;5;010m%s\033[0m"
.
To replicate how PHP's own highlight_string outputs HTML, those strings would look like "<span style='color: black;'>%s</span>"
.
Yes: literally change the color of your terminal. Not with PHP. In the terminal's settings or options or whatever.
ok, not expected, let me keep trying on my own. thanks all the same.
the library is now ready:
https://github.com/arcanisgk/BOH-Basic-Output-Handler