如何在PHP中打印彩色字符串

时间:2018-06-02 13:05:46

标签: php string

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

  1. 黄色,当char是奇数时;
  2. 蓝色,当char是偶数时;
  3. red,当char是元音时;
  4. 绿色,char是辅音;
  5. 例如:$string = "hi12";

    1. h =绿色
    2. i = red
    3. 1 =黄色
    4. 2 =蓝色
    5. 我已经尝试过这个但似乎不起作用:

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

1 个答案:

答案 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;
相关问题