Hello! Instead of 'Hello World!' displays ! Tell me ...

$str = 'Привет Мир!'; for($i=0; $i<strlen($str); $i++) { echo $str[$i], ' '; } 

And this is how it displays normally:

 $str = 'Привет Мир!'; echo $str; 

    3 answers 3

    Use the mb_substr function:

     $str = 'Привет Мир!'; for($i=0; $i<strlen($str); $i++) { echo mb_substr($str, $i, 1, 'utf-8'), ' '; } 

    In more detail:

    1. Wrong output when using array indexing on UTF-8 string
    2. mb_substr
    • Thank you, Pavel Azanov! Everything worked out! - abcdf
    • I insert my code into curly braces, and for some reason I don’t have it displayed here on the forum formatted. Why? What should be done? - abcdf
    • $ str = 'Hello World!'; echo $ str; - abcdf
    • @anton: To format a code, select it and then press the {} button in the editor. If the answer suits you, you can accept it by clicking on the check mark under the vote counter for / against the answer. - Pavel Azanov 8:36 pm

    In addition to all the scams, you still need to send the headers:

     header('Content-Type: text/html; charset=utf-8'); 

    If the code is written in an empty file.

    If it is UTF-8 , then strlen for Cyrillic characters will be 22 characters long (maybe 20) because the characters are encoded in 2 bytes, because we need the function mb_strlen . Try it.

      Set the file encoding to utf-8 and in the root of your project or site create a .htaccess file and insert the line AddDefaultCharset utf8 into it

      • I have done so. Here, apparently, the trick is that the string is output as an array ... - abcdf
      • mountpoint copy the code, test it yourself. If the output ??? then the problem is not in the encoding. - abcdf
      • Yes, UTF-8 without BOM. Does this code work for you? - abcdf
      • @anton, yes, I have the same crap ... strange - mountpoint