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

有帮助吗?

解决方案

我不知道在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);

其他提示

在str_replace函数溶液不会在颜色被“嵌套”的情况下工作,因为在ANSI颜色码,一个ESC [0米复位是所有的重置所有属性需要的。虽然在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终端的问题在这里拍摄: http://drupal.org/node/709742

我也找PHP库可以轻松地做到这一点。

P.S。如果你想ANSI转义序列转换成PNG /图像,你可以使用 AnsiLove

有库现在: ANSI-到HTML

和非常容易使用

$converter = new AnsiToHtmlConverter();
$html = $converter->convert($ansi);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top