这是与 this one 类似的问题.我想将 ANSI 转义序列(尤其是颜色)转换为 HTML。但是,我想使用 PHP 来完成此操作。是否有任何库或示例代码可以执行此操作?如果没有,有什么可以让我参与定制解决方案的吗?
最佳答案
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);
(取 self 的 Drush 终端问题:http://drupal.org/node/709742)
我也在寻找可以轻松完成此操作的 PHP 库。
附言如果要将 ANSI 转义序列转换为 PNG/图像,可以使用 AnsiLove .
关于php - 使用 PHP 将 ANSI 转义序列转换为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1375683/