使用PHP将ANSI转义序列转换为HTML

Tra*_*ale 7 html php terminal-color ansi-escape

这是一个类似的问题这一个.我想将ANSI转义序列(特别是颜色)转换为HTML.但是,我想用PHP完成这个.是否有任何库或示例代码可以执行此操作?如果没有,任何可以让我参与自定义解决方案的东西?

Hen*_*wan 8

str_replace解决方案在颜色"嵌套"的情况下不起作用,因为在ANSI颜色代码中,一个ESC [0m重置是重置所有属性所需的全部.在HTML中,您需要SPAN结束标记的确切数量.

适用于"嵌套"用例的解决方法如下:

  // 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);
Run Code Online (Sandbox Code Playgroud)

(摘自我的Drush Terminal问题:http://drupal.org/node/709742)

我也在寻找PHP库来轻松完成这项工作.

PS如果要将ANSI转义序列转换为PNG /图像,可以使用AnsiLove.


Ern*_*ius 5

现在有库:ansi-to-html

而且非常容易使用:

$converter = new AnsiToHtmlConverter();
$html = $converter->convert($ansi);
Run Code Online (Sandbox Code Playgroud)


sou*_*rge 4

我不知道 PHP 有这样的库。但是,如果您有一致的输入和有限的颜色,您可以使用简单的方法来完成它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);
Run Code Online (Sandbox Code Playgroud)