可以通过使用ANSI转义序列来实现。ANSI转义序列是一种控制终端输出的特殊字符序列。具体实现代码如下:
<?php
function coloredPrint($string, $color) {
$colors = [
'black' => '0;30',
'dark_gray' => '1;30',
'blue' => '0;34',
'light_blue' => '1;34',
'green' => '0;32',
'light_green' => '1;32',
'cyan' => '0;36',
'light_cyan' => '1;36',
'red' => '0;31',
'light_red' => '1;31',
'purple' => '0;35',
'light_purple' => '1;35',
'brown' => '0;33',
'yellow' => '1;33',
'light_gray' => '0;37',
'white' => '1;37'
];
$coloredString = "\033[" . $colors[$color] . "m" . $string . "\033[0m";
echo $coloredString . PHP_EOL;
}
$lines = [
'Line 1',
'Line 2',
'Line 3',
'Line 4',
'Line 5'
];
foreach ($lines as $index => $line) {
$color = $index % 2 == 0 ? 'green' : 'blue';
coloredPrint($line, $color);
}
?>
上述代码定义了一个coloredPrint()
函数,它接受两个参数:要打印的字符串和要使用的颜色。颜色通过关联数组存储,每种颜色对应一个ANSI转义序列。在函数内部,使用"\033[颜色序列m"
将字符串前后包裹起来,实现输出不同颜色的效果。
代码中使用了一个示例数组$lines
,包含了要打印的每行内容。然后通过循环遍历每行,根据行号决定颜色(偶数行为绿色,奇数行为蓝色),调用coloredPrint()
函数进行打印。
注意:由于ANSI转义序列只在支持的终端上生效,因此在一些特定环境下可能无法展示出不同颜色的效果。
领取专属 10元无门槛券
手把手带您无忧上云