Last active
May 25, 2018 09:01
-
-
Save hisune/98652966828b7111e9b10602eff4f946 to your computer and use it in GitHub Desktop.
Light up your code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 按颜色输出 | |
* 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