简体   繁体   中英

my function doesn't return some letters even though included in utf-8 (vscode, php)

It's supposed to spit out each letter of a string, if it's in one of the objects keys, but those odd characters æø etc. doesn't show at all and I get results like: ltkai. instead of: lætkaiø.

I'm using vscode and php (installed with scoop).

  • I've attempted both UTF-8 and UTF-8 with BOM encoding in vscode.

  • I already use meta charset="utf-8".

  • I've tried with charset="" header().

  • I've used mbstring extension to detect if it's utf-8 or not, and it always register as utf and shows the odd letters with loops and as a whole string, but if it's in my if stmt, it just doesn't register as utf, and utf_encode doesn't work (it's like it registers them as utf already, encodes them then, and gives odder letters back).

  • I've also used property_exists() outside my function, and it works there, but still not inside.

  • I've tried utf_encode, but also does not work.

     $name = 'lætkaiø'; $vocals = (object) ['æ' => 4, 'i' => 3, 'ø' => 3, 'a' => 4]; $konsonants = (object) ['t' => 5, 'l' => 6, 'k' => 3]; function letters($name, $konsonants, $vocals) { $letterarr = str_split($name); foreach($letterarr as $letter){ if (property_exists($konsonants, $letter)){ echo($letter); } if (property_exists($vocals, $letter)){ echo($letter); } } }

If anybody has any ideas why this is happening or how to solve it? Thank you:)

str_split operates on bytes, and characters such as æ take up more than 1 byte in UTF-8.

So if you str_split these characters, they basically get 'split in two' into an invalid character. Just run count() on $letterarr to see that there are 9 items in the array, instead of the expected 7.

The solution is to use PHP's string functions that are UTF-8 aware. Simply changing str_split into mb_str_split will fix your code sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM