我想用这种颜色打印一个字符串:
例如:$string = "hi12";
我已经尝试过这个但似乎不起作用:
$string = "hi12"; <br>
$strCol = ""; <br>
$char = ""; <br>
$color = ""; <br>
for($i = 0; $i < strlen($string); $i++){
$char = $string[$i];
if(is_numeric($char)){
if(($char % 2) == 1){
$color = "<p style='color:yellow;'>" + $char + "</p>";
$strCol .= $color;
}
else if(($char % 2) == 0){
$color = "<p style='color:blue;'>" + $char + "</p>";
$strCol .= $color;
}
}
else{
if(preg_match('/^[aeiou]/i', $char)){
$color = "<p style='color:red;'>" + $char + "</p>";
$strCol .= $color;
}
else{
$color = "<p style='color:green;'>" + $char + "</p>";
$strCol .= $color;
}
}
}
echo $strCol;
答案 0 :(得分:0)
$isGreen = false;
$isRed = false;
$isYellow = false;
$isBlue = false;
$string = 'some text with space';
$letterCount = strlen($string) - substr_count($string, ' ');
if (0 == $letterCount % 4) {
$isBlue = true;
} elseif (1 == $letterCount % 4) {
$isGreen = true;
} elseif (2 == $letterCount % 4) {
$isRed = true;
} else {
$isYellow = true;
}
for ($i = strlen($string) - 1; $i >= 0; $i--) {
$letter = substr($string, $i, 1);
if (' ' == $letter) {
continue;
}
if ($isGreen) {
$colour = 'green';
$isGreen = !$isGreen;
$isBlue = !$isBlue;
} elseif ($isRed) {
$colour = 'red';
$isGreen = !$isGreen;
$isRed = !$isRed;
} elseif ($isYellow) {
$colour = 'yellow';
$isRed = !$isRed;
$isYellow = !$isYellow;
} else {
$colour = 'blue';
$isBlue = !$isBlue;
$isYellow = !$isYellow;
}
$string = substr_replace($string, sprintf('<span style="color:%s">%s</span>', $colour, $letter) , $i, 1);
}
echo $string;