Skip to content

Instantly share code, notes, and snippets.

@ralphschindler
Created December 26, 2014 14:38
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 ralphschindler/f0c93dc70fb05c3c7cc4 to your computer and use it in GitHub Desktop.
Save ralphschindler/f0c93dc70fb05c3c7cc4 to your computer and use it in GitHub Desktop.
CLI Colorization via HTML style tagging function. This solution is UNLICENSED, feel free to do whatever you want with it.
<?php
/** @license http://unlicense.org/UNLICENSE */
function colorize($string, $useAnsi = null)
{
if (is_null($useAnsi)) {
$useAnsi = function_exists('posix_isatty');
}
$tags = array(
'reset' => 0, 'bold' => 1, 'dark' => 2, 'italic' => 3, 'underline' => 4, 'blink' => 5, 'reverse' => 7, 'concealed' => 8,
'black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37,
'bg_black' => 40, 'bg_red' => 41, 'bg_green' => 42, 'bg_yellow' => 43, 'bg_blue' => 44, 'bg_magenta' => 45, 'bg_cyan' => 46, 'bg_white' => 47,
'dark_gray' => 90, 'light_red' => 91, 'light_green' => 92, 'light_yellow' => 93, 'light_blue' => 94, 'light_magenta' => 95, 'light_cyan' => 96, 'white' => 97,
'bg_dark_gray' => 100, 'bg_light_red' => 101, 'bg_light_green' => 102, 'bg_light_yellow' => 103, 'bg_light_blue' => 104, 'bg_light_magenta' => 105, 'bg_light_cyan' => 106, 'bg_white' => 107,
);
$matches = array();
$regex = '#(<(' . implode('|', array_keys($tags)) . ')\b[^>]*>)(.+?)</\2?>#si';
while (preg_match_all($regex, $string, $matches)) {
foreach ($matches[0] as $index => $matchFull) {
$replacement = ($useAnsi) ? '=START(' . $tags[$matches[2][$index]] . ')=' . $matches[3][$index] . '=END=' : $matches[3][$index];
$string = str_replace($matchFull, $replacement, $string);
}
}
$tokens = preg_split('#(=START\(\d+\)=|=END=?)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$codeStack = array();
foreach ($tokens as $tokenIndex => $token) {
if (strpos($token, '=START(') === 0) {
$codeStack[] = $codeNum = substr($token, 7, -2);
$tokens[$tokenIndex] = "\033[{$codeNum}m";
} elseif (strpos($token, '=END=') === 0) {
array_shift($codeStack);
$tokens[$tokenIndex] = "\033[" . (($codeStack) ? implode(',', $codeStack) : '0') . 'm';
}
}
return implode('', $tokens);
}
// example usage
echo colorize("<red>Red</red> <bold>Bold</bold> <bold><blue>Blue and Bold</blue></bold>\n");
echo colorize("<light_blue>light blue</light_blue> vs. <blue>blue</blue>\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment