Skip to content

Instantly share code, notes, and snippets.

@hisune
Last active May 25, 2018 09:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hisune/98652966828b7111e9b10602eff4f946 to your computer and use it in GitHub Desktop.
Light up your code
/**
* 按颜色输出
* https://hisune.com/view/60/php-cli-colors-output
* usage: color('error %e, notice %n, normal %s', 'xx', 'oo', 'yes ppg')
* @param $format
* @param mixed ...$args
* @return mixed
*/
function color($format, ...$args)
{
$colors = [
'%e' => "\e[31m%s\e[0m", // error
'%n' => "\e[34m%s\e[0m", // notice
'%o' => "\e[32m%s\e[0m", // ok
'%b' => "\e[33m%s\e[0m", // Brown
'%s' => "%s", // normal
];
while(true){
$indexes = [];
foreach($colors as $tag => $addOn){
$position = strpos($format, $tag);
if($position !== false){
$indexes[$tag] = $position;
}
}
if(!$indexes){
break;
}
$min = min($indexes);
$index = array_keys($indexes, $min);
$replacement = array_shift($args);
$format = substr_replace($format, sprintf($colors[$index[0]], $replacement), $min, 2);
}
echo $format . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment