Converting ANSI escape sequences to HTML using PHP

我是研究僧i 提交于 2019-12-05 23:57:53

问题


This is a similar question to this one. I would like to convert ANSI escape sequences, especially for color, into HTML. However, I would like to accomplish this using PHP. Are there any libraries or example code out there that do this? If not, anything that can get me part way to a custom solution?


回答1:


I don't know of any such library in PHP. But if you have a consistent input with limited colors, you can accomplish it using a simple 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);



回答2:


The str_replace solution wouldn't work in cases where colors are "nested", because in ANSI color codes, one ESC[0m reset is all that's needed to reset all attributes. While in HTML, you need the exact number of SPAN closing tags.

A workaround that works the "nested" use case is below:

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

(taken from my Drush Terminal issue here: http://drupal.org/node/709742 )

I'm also looking for the PHP library to do this easily.

P.S. If you want to convert ANSI escape sequences to PNG/image, you can use AnsiLove.




回答3:


There are library now: ansi-to-html

And very easy to use:

$converter = new AnsiToHtmlConverter();
$html = $converter->convert($ansi);


来源:https://stackoverflow.com/questions/1375683/converting-ansi-escape-sequences-to-html-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!