Jam*_*989 5 php preg-replace command-line-interface
我正在尝试从日志中解析行并输出 html 并希望颜色代码起作用。
我在网上发现这门课应该可以用,但它不会给任何东西上色,也不会删除控制代码。它应该用等效的 html 替换控制代码,但完全忽略它输出
[0;35;22m/plugins: [0;37;1mGets a list of plugins running on the server[m
Run Code Online (Sandbox Code Playgroud)
这是课程
<?php
function bashColortoHtml($string) {
$ret = false;
if(!empty($string)) {
$_colorPattern = array(
'/\\033\[1;33m(.*?)\\033\[0m/s',
'/\\033\[0;31m(.*?)\\033\[0m/s',
'/\\033\[0;34m(.*?)\\033\[0m/s',
'/\\033\[0;36m(.*?)\\033\[0m/s',
'/\\033\[0;35m(.*?)\\033\[0m/s',
'/\\033\[0;33m(.*?)\\033\[0m/s',
'/\\033\[1;37m(.*?)\\033\[0m/s',
'/\\033\[0;30m(.*?)\\033\[0m/s',
'/\\033\[0;32m(.*?)\\033\[0m/s'
);
$_colorReplace = array(
'<span class="yellow">$1</span>',
'<span class="red">$1</span>',
'<span class="blue">$1</span>',
'<span class="cyan">$1</span>',
'<span class="purple">$1</span>',
'<span class="brown">$1</span>',
'<span class="white">$1</span>',
'<span class="black">$1</span>',
'<span class="green">$1</span>'
);
$ret = preg_replace($_colorPattern, $_colorReplace, $string);
}
return $ret;
}
?>
<?php
$output = bashColortoHtml('[0;35;22m/plugins: [0;37;1mGets a list of plugins running on the server[m');
echo $output;
?>
Run Code Online (Sandbox Code Playgroud)
这个类有什么问题和/或有什么更好的方法可以用 php 做到这一点
我今天不得不解决同样的问题,并编写了这个简单明了的函数。请务必检查,如果它符合您的需求,您可能需要添加一些案例。
//
// Converts Bashoutput to colored HTML
//
function convertBash($code) {
$dictionary = array(
'[1;30m' => '<span style="color:black">',
'[1;31m' => '<span style="color:red">',
'[1;32m' => '<span style="color:green">',
'[1;33m' => '<span style="color:yellow">',
'[1;34m' => '<span style="color:blue">',
'[1;35m' => '<span style="color:purple">',
'[1;36m' => '<span style="color:cyan">',
'[1;37m' => '<span style="color:white">',
'[m' => '</span>'
);
$htmlString = str_replace(array_keys($dictionary), $dictionary, $code);
return $htmlString;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2977 次 |
| 最近记录: |