Instantly share code, notes, and snippets.

@hisune /color.php
Last active May 25, 2018

Embed
What would you like to do?
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