views:

657

answers:

2

This is a similar question to this one. I would like to convert ANSI escape sequences, especially for color, into HTML. However, I would like to accomplish this using PHP. Are there any libraries or example code out there that do this? If not, anything that can get me part way to a custom solution?

+2  A: 

I don't know of any such library in PHP. But if you have a consistent input with limited colors, you can accomplish it using a simple str_replace():

$dictionary = array(
    'ESC[01;34' => '<span style="color:blue">',
    'ESC[01;31' => '<span style="color:red">',
    'ESC[00m'   => '</span>' ,
);
$htmlString = str_replace(array_keys($dictionary), $dictionary, $shellString);
soulmerge
I'm really looking for a more general solution, but this is good and I may end up going this route.
Travis Beale
+1  A: 

The str_replace solution wouldn't work in cases where colors are "nested", because in ANSI color codes, one ESC[0m reset is all that's needed to reset all attributes. While in HTML, you need the exact number of SPAN closing tags.

A workaround that works the "nested" use case is below:

  // Ugly hack to process the color codes
  // We need something like Perl's HTML::FromANSI
  // http://search.cpan.org/perldoc?HTML%3A%3AFromANSI
  // but for PHP
  // http://ansilove.sourceforge.net/ only converts to image :(
  // Technique below is from:
  // http://stackoverflow.com/questions/1375683/converting-ansi-escape-sequences-to-html-using-php/2233231
  $output = preg_replace("/\x1B\[31;40m(.*?)(\x1B\[0m)/", '<span style="color: red">$1</span>$2', $output);
  $output = preg_replace("/\x1B\[1m(.*?)(\x1B\[0m)/", '<b>$1</b>$2', $output);
  $output = preg_replace("/\x1B\[0m/", '', $output);

(taken from my Drush Terminal issue here: http://drupal.org/node/709742 )

I'm also looking for the PHP library to do this easily.

P.S. If you want to convert ANSI escape sequences to PNG/image, you can use AnsiLove.

Hendy Irawan