Charset setting difficulty in PHP

Asked

Viewed 192 times

0

I tried to make a program that assigns a certain color sequence to all characters, but the result is not as expected and all indicates that it has to do with the definition of "charset".

Then I’ll put the code and put together an image of the test output in the expectation that someone will tell me what I’m doing wrong.

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8" />
    <title>Mudar a cor das letras</title>
</head>
<body>
    <?php
      header('Content-type: text/html; charset=utf-8');
      $cor=array("blue","#00b300","red","black","#ff9900","#ff0066",
                 "#cc00cc","#00ccff","#336600","#996600","#ff00ff","#66ccff");
      $nelcor=count($cor);
      $texto="educação123";
      echo $texto; echo "<br/>";
      $nletras1=strlen($texto);//??? conta mais caracteres ex: ã=2
      $nletras=mb_strlen($texto, 'utf8');
      echo "strlen= ".$nletras1."<br>"."mb_strlen= ".$nletras."<br>"; 

      if ($nletras==0) {
        echo "Não há texto"; goto fim;
      }

      $vtexto = str_split($texto);//transformar string (cadeia ou texto) em array 
      (vector)
      $contador = 0; //ler letra a letra todo o texto
      while($contador <= $nletras-1) {
          $ncor=$contador%$nelcor;
          echo "<font size='5' color=$cor[$ncor]>$vtexto[$contador]</font>"; 
          $contador++;
      } 
      fim:;
    ?>
</body>
</html>

printscreen com a tela do navegado.

1 answer

0


The str_split does not work with Unicode

Use preg_split('//u', $texto, null, PREG_SPLIT_NO_EMPTY); and save the document as UTF-8 NO GOOD, thus:

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8" />
<title>Mudar a cor das letras</title>
</head>
<body>
<?php
header('Content-type: text/html; charset=utf-8');
$cor=array("blue","#00b300","red","black","#ff9900","#ff0066",
"#cc00cc","#00ccff","#336600","#996600","#ff00ff","#66ccff");
$nelcor=count($cor);
$texto="educação123";
echo $texto;echo "<br/>";
$nletras1=strlen($texto);//??? conta mais caracteres ex: ã=2
$nletras=mb_strlen($texto, 'utf8');
echo "strlen= ".$nletras1."<br>"."mb_strlen= ".$nletras."<br>"; 
if ($nletras==0) {
echo "Não há texto"; goto fim;
}
$vtexto = preg_split('//u', $texto, null, PREG_SPLIT_NO_EMPTY);//transformar string (cadeia ou texto) em array 

$contador = 0; //ler letra a letra todo o texto
while($contador <= $nletras-1) {
$ncor=$contador%$nelcor;
echo "<font size='5' color=$cor[$ncor]>$vtexto[$contador]</font>"; 
$contador++;
} 
fim:;
?>
</body>
</html>
  • Solved and much faster than I thought. Note: I used Notepad++ with utf-8 encoding without BOM

  • How or where I make this appointment?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.