【问题标题】:How to print a colored string in PHP如何在 PHP 中打印彩色字符串
【发布时间】:2018-11-12 09:51:06
【问题描述】:

我想用这种颜色打印一个字符串:

  1. 黄色,当字符为奇数时;
  2. 蓝色,当字符为偶数时;
  3. 红色,当字符是元音时;
  4. green,a char 是辅音;

例如:$string = "hi12";

  1. h = 绿色
  2. i = 红色
  3. 1 = 黄色
  4. 2 = 蓝色

我已经尝试过,但它似乎不起作用:

$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;

【问题讨论】:

  • PHP 的连接运算符是. 而不是+。您的代码正在尝试将 html 标记和字符的整数值相加,从而为您提供输出 0012。另请注意,&lt;p&gt; 标记将以新行中的每个字符结束。也许这就是你想要的,但如果不是,那么&lt;span&gt; 标签可能更有用。
  • 现在可以了,非常感谢
  • 除此之外:您应该考虑使用单独的样式规则而不是内联规则。将 css 组分配给段落标签,然后在单独的 css 块或文件中为分配给这些组的元素设置样式。

标签: php string


【解决方案1】:
$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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多