<?php
/**
 * Very simple output colorizer. Only changes the foreground color.
 * Tokens take the form {colorname}.
 *
 * Bright colors start with 'b', as in 'bgreen' and 'bblue'.
 *
 * You can escape brackets using double brackets {{ and }}
 *
 * PHP >= 5.3.0 (but could easily be modified to work with earlier versions)
 *
 * @param string $str The text to colorize
 * @return string
 */
function colorize($str) {
  static $tmp = array('#{{#TEMP#', '#TEMP#}}#');
  static $map = array(
    'end'        => '0;0',
    'black'      => '0;30',
    'red'        => '0;31',
    'green'      => '0;32',
    'brown'      => '0;33',
    'darkyellow' => '0;33',
    'blue'       => '0;34',
    'purple'     => '0;35',
    'cyan'       => '0;36',
    'gray'       => '0;37',
    'darkgray'   => '1;30',
    'bred'       => '1;31',
    'bgreen'     => '1;32',
    'yellow'     => '1;33',
    'bblue'      => '1;34',
    'magenta'    => '1;35',
    'bpurple'    => '1;35',
    'bcyan'      => '1;36',
    'white'      => '1;37',
  );
  static $rx;
  $rx or ($rx = sprintf('/\\{(%s)\\}/', implode('|', array_keys($map))));
  $str = str_replace(array('{{', '}}'), $tmp, $str);
  $str = preg_replace_callback(
    $rx,
    function($m) use ($map) {
      return isset($map[$m[1]]) ? "\033[{$map[$m[1]]}m" : $m[0];
    },
    $str
  );
  return str_replace($tmp, array('{', '}'), $str);
}