Thursday, January 28, 2016

echo color text in console

echo color text in console by using some escape sequences:

myecho('Hello World', 'green', 'background');

function myecho($msg, $color = 'green', $ground = 'foreground') {
  $colorArr = array();
  $colorArr['foreground'] = array(
    'black' => '0;30',
    'dark_gray' => '1;30',
    'red' => '0;31',
    'bold_red' => '1;31',
    'green' => '0;32',
    'bold_green' => '1;32',
    'brown' => '0;33',
    'yellow' => '1;33',
    'blue' => '0;34',
    'bold_blue' => '1;34',
    'purple' => '0;35',
    'bold_purple' => '1;35',
    'cyan' => '0;36',
    'bold_cyan' => '1;36',
    'white' => '1;37',
    'bold_gray' => '0;37',
  );

  $colorArr['background'] = array(
    'black' => '40',
    'red' => '41',
    'magenta' => '45',
    'yellow' => '43',
    'green' => '42',
    'blue' => '44',
    'cyan' => '46',
    'light_gray' => '47',
  );

  if (isset($colorArr[$ground][$color])) {
    echo "\033[" . $colorArr[$ground][$color] . "m" . $msg . "\033[0m";
  }
  else {
    echo $msg;
  }
}

Note: Google bash color for detail.

Reference:

http://stackoverflow.com/questions/1691646/php-echo-text-color

http://www.ingeniousmalarkey.com/2011/02/add-color-to-php-echo-in-cli.html

No comments: