7

这是一个与此类似的问题。我想将 ANSI 转义序列(尤其是颜色)转换为 HTML。但是,我想使用 PHP 来完成此操作。是否有任何库或示例代码可以做到这一点?如果没有,有什么能让我参与定制解决方案的吗?

4

3 回答 3

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

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

我也在寻找 PHP 库来轻松地做到这一点。

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

于 2010-02-09T23:12:08.770 回答
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);
于 2009-09-03T20:25:02.360 回答
4

现在有图书馆:ansi-to-html

并且非常易于使用:

$converter = new AnsiToHtmlConverter();
$html = $converter->convert($ansi);
于 2017-08-05T10:54:56.093 回答