Created
January 27, 2012 10:52
-
-
Save drm/1688261 to your computer and use it in GitHub Desktop.
ANSI colorized output
This file contains 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
<?php | |
/** | |
* Write colorized text to a stream | |
* | |
* @param $stream | |
* @param $text | |
* @param $args | |
*/ | |
function cprintf($stream, $text, $args = null) { | |
$args = array_slice(func_get_args(), 2);; | |
$s = vsprintf($text, $args); | |
fwrite( | |
$stream, | |
preg_replace_callback( | |
'/<([^>]+)>(.*?)<\/\1>/', | |
function($m) { | |
switch($m[1]) { | |
case 'error': | |
return sprintf("\033[0;31m%s\033[0m", $m[2]); | |
case 'warning': | |
return sprintf("\033[33m%s\033[0m", $m[2]); | |
case 'info': | |
return sprintf("\033[1m%s\033[0m", $m[2]); | |
case 'ok': | |
return sprintf("\033[32m%s\033[0m", $m[2]); | |
default: | |
return $m[2]; | |
} | |
}, | |
$s | |
) | |
); | |
} | |
/** | |
* Write a colorized line to the console. | |
* | |
* @param $stream | |
* @param $text | |
* @param null $args | |
*/ | |
function lcprintf($stream, $text, $args = null) { | |
$args = func_get_args(); | |
fwrite($stream, "\033[s"); // save cursor | |
call_user_func_array('cprintf', $args); | |
fwrite($stream, "\033[K\033[u");// restore cursor | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment