如何为PHP CLI启用颜色?

Bar*_*veg 7 php bash shell ubuntu command-line-interface

如何为CLI的输出启用颜色?下面是在Ubuntu上运行的.

在此输入图像描述

如果您看到屏幕截图,很明显终端的颜色已启用.并且,如果我打电话echo,它不会使结果着色,但如果我使用echo -e,它会着色.
我检查了手册页echo,并且-e意味着启用反斜杠转义的解释
如何为PHP CLI启用此选项?

小智 29

对于比较懒的人来说

function colorLog($str, $type = 'i'){
    switch ($type) {
        case 'e': //error
            echo "\033[31m$str \033[0m\n";
        break;
        case 's': //success
            echo "\033[32m$str \033[0m\n";
        break;
        case 'w': //warning
            echo "\033[33m$str \033[0m\n";
        break;  
        case 'i': //info
            echo "\033[36m$str \033[0m\n";
        break;      
        default:
        # code...
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)


jay*_*xhj 17

首先我们使用转义字符,以便我们可以实际定义输出颜色.这是通过\ 033(\ e)完成的.然后我们打开[31m的颜色语句.在这种情况下红色."一些彩色文本"将是以不同颜色输出的文本.之后我们必须用\ 033 [0m]关闭颜色语句.

php -r 'echo "\033[31m some colored text \033[0m some white text \n";'
Run Code Online (Sandbox Code Playgroud)

  • 单引号不能顺便说一句:)使用双引号 (2认同)
  • +1 超级有帮助。仅供参考,如果其他人需要[帮助查找颜色代码](https://www.shellhacks.com/bash-colors/)。 (2认同)

Fan*_*nto 11

经过一些实验,我编写了这些代码:

function formatPrint(array $format=[],string $text = '') {
  $codes=[
    'bold'=>1,
    'italic'=>3, 'underline'=>4, 'strikethrough'=>9,
    'black'=>30, 'red'=>31, 'green'=>32, 'yellow'=>33,'blue'=>34, 'magenta'=>35, 'cyan'=>36, 'white'=>37,
    'blackbg'=>40, 'redbg'=>41, 'greenbg'=>42, 'yellowbg'=>44,'bluebg'=>44, 'magentabg'=>45, 'cyanbg'=>46, 'lightgreybg'=>47
  ];
  $formatMap = array_map(function ($v) use ($codes) { return $codes[$v]; }, $format);
  echo "\e[".implode(';',$formatMap).'m'.$text."\e[0m";
}
function formatPrintLn(array $format=[], string $text='') {
  formatPrint($format, $text); echo "\r\n";
}

//Examples:
formatPrint(['blue', 'bold', 'italic','strikethrough'], "Wohoo");
formatPrintLn(['yellow', 'italic'], " I'm invicible");
formatPrintLn(['yellow', 'bold'], "I'm invicible");

Run Code Online (Sandbox Code Playgroud)

只需复制并粘贴上面的代码即可...享受吧:)