PHP - Loop accentuation problem in a string

Asked

Viewed 87 times

2

I’m having trouble with loop in strings with special characters, someone could help me?

Follow the example:

$letras = 'nós';
$numero = strlen($letras);
for($j = 0; $j < $numero; $j++){
    echo $letras[$j]."-";
}

Follow the result of the above code: http://codepad.org/3EZ5bpUl

3 answers

2


Try to do so:

$letras = utf8_decode('nós');
$numero = strlen($letras);
for($j = 0; $j < $numero; $j++){
   echo utf8_encode($letras[$j])."-";
}

2

Use the utf8_decode to convert the string and after this the utf8_encode to make the impression in the right way.

 <?php
    $letras = utf8_decode('nós');
    $numero = strlen($letras);
    for($j = 0; $j < $numero; $j++){
        echo utf8_encode($letras[$j]."-");
    }

2

You can also use the mb_substr, or even regex.


$frase = 'nós';
$tamanho = mb_strlen($frase);

for($posicao = 0; $posicao < $tamanho; $posicao++){

    echo mb_substr($frase, $posicao, 1, "UTF-8") . '-';

}

Test it out here

Thus the mb_substr will get the letter of $posicao, as it is set to UTF-8 there is no problem with multibyte characters.

This is also compatible with phrases like 您是否使用了翻译, he will return:

您-是-否-使-用-了-翻-译-

The other answers, using utf8_decode, would return ?-?-?-?-?-?-?-?-.


Another case would be to create something like the str_split, but compatible with characters with more than one byte, there is no mb_str_split.

You could use the preg_split.

$frase = 'nós';
$tamanho = mb_strlen($frase);

$letras = array_filter(preg_split('//u', $frase));

foreach($letras as $letra){

    echo $letra . '-';

}

Test it out here.

In this case the preg_split is responsible for creating an array, for each Unicode, so it will create a:

array(5) {
  [0]=>
  string(0) ""
  [1]=>
  string(1) "n"
  [2]=>
  string(2) "ó"
  [3]=>
  string(1) "s"
  [4]=>
  string(0) ""
}

As we do not want the empty spaces, we remove with the array_filter.

Browser other questions tagged

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