color.php

  1. <?php
  2.  
  3. class ansi {
  4. public static function set_back_color($color_name, $return = FALSE) {
  5. $colors = array(
  6. 'black' => '40',
  7. 'red' => '41',
  8. 'green' => '42',
  9. 'yellow' => '43',
  10. 'blue' => '44',
  11. 'magenta' => '45',
  12. 'cyan' => '46',
  13. 'white' => '47',
  14. );
  15.  
  16. if ('bright' == substr($color_name, 0, 6)) {
  17. $suffix = ';1';
  18. $color_name = substr($color_name, 6);
  19. } elseif ('dim' == substr($color_name, 0, 3)) {
  20. $suffix = ';2';
  21. $color_name = substr($color_name, 3);
  22. } else {
  23. $suffix = FALSE;
  24. };
  25.  
  26. $result = sprintf(chr(27).'[%sm', $colors[$color_name].$suffix);
  27.  
  28. if ((bool) $return)
  29. return $result;
  30. else
  31. echo $result;
  32. }
  33.  
  34. public static function set_fore_color($color_name, $return = FALSE) {
  35. $colors = array(
  36. 'reset' => '0',
  37.  
  38. 'black' => '30',
  39. 'red' => '31',
  40. 'green' => '32',
  41. 'yellow' => '33',
  42. 'blue' => '34',
  43. 'magenta' => '35',
  44. 'cyan' => '36',
  45. 'white' => '37',
  46. );
  47.  
  48. if ('bright' == substr($color_name, 0, 6)) {
  49. $suffix = ';1';
  50. $color_name = substr($color_name, 6);
  51. } elseif ('dim' == substr($color_name, 0, 3)) {
  52. $suffix = ';2';
  53. $color_name = substr($color_name, 3);
  54. } else {
  55. $suffix = FALSE;
  56. };
  57.  
  58. $result = sprintf(chr(27).'[%sm', $colors[$color_name].$suffix);
  59.  
  60. if ((bool) $return)
  61. return $result;
  62. else
  63. echo $result;
  64. }
  65.  
  66. public static function set_color($fore_color = FALSE, $back_color = FALSE, $return = FALSE) {
  67. if (FALSE === $fore_color AND FALSE === $back_color) {
  68. return self::set_fore_color('reset', $return);
  69. } else {
  70. $result = '';
  71.  
  72. if ((bool) $fore_color)
  73. $result .= self::set_fore_color($fore_color, $return);
  74.  
  75. if ((bool) $back_color)
  76. $result .= self::set_back_color($back_color, $return);
  77.  
  78. return $result;
  79. }
  80. }
  81.  
  82. public static function cprintf($fore_color = FALSE, $back_color = FALSE, $format) {
  83. // Get the args after $format for the vprintf call.
  84. $args = func_get_args();
  85. $args = array_slice($args, 3);
  86.  
  87. self::set_color($fore_color, $back_color);
  88.  
  89. vprintf($format, $args);
  90.  
  91. self::set_color();
  92. }
  93.  
  94. public static function csprintf($fore_color = FALSE, $back_color = FALSE, $format) {
  95. // Get the args after $format for the vprintf call.
  96. $args = func_get_args();
  97. $args = array_slice($args, 3);
  98.  
  99. $result = self::set_color($fore_color, $back_color, TRUE);
  100.  
  101. $result .= vsprintf($format, $args);
  102.  
  103. $result .= self::set_color(FALSE, FALSE, TRUE);
  104.  
  105. return $result;
  106. }
  107. }
  108.