Home » Php » Converting ANSI escape sequences to HTML using PHP

Converting ANSI escape sequences to HTML using PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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);

Answer:

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.

Answer:

There are library now: ansi-to-html

And very easy to use:

$converter = new AnsiToHtmlConverter();
$html = $converter->convert($ansi);