【发布时间】:2010-11-25 10:19:51
【问题描述】:
这是与this one 类似的问题。我想将 ANSI 转义序列(尤其是颜色)转换为 HTML。但是,我想使用 PHP 来完成这个。是否有任何库或示例代码可以做到这一点?如果没有,有什么可以让我参与定制解决方案的吗?
【问题讨论】:
标签: php html terminal-color ansi-escape
这是与this one 类似的问题。我想将 ANSI 转义序列(尤其是颜色)转换为 HTML。但是,我想使用 PHP 来完成这个。是否有任何库或示例代码可以做到这一点?如果没有,有什么可以让我参与定制解决方案的吗?
【问题讨论】:
标签: php html terminal-color ansi-escape
现在有图书馆:ansi-to-html
而且非常容易使用:
$converter = new AnsiToHtmlConverter();
$html = $converter->convert($ansi);
【讨论】:
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 库来轻松做到这一点。
附:如果要将ANSI转义序列转换为PNG/图像,可以使用AnsiLove。
【讨论】:
我不知道 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);
【讨论】: