Converting ANSI escape sequences to HTML using PHP

不打扰是莪最后的温柔 提交于 2019-12-04 05:12:11

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

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.

There are library now: ansi-to-html

And very easy to use:

$converter = new AnsiToHtmlConverter();
$html = $converter->convert($ansi);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!