Php length of cyrillic string doubles its value

2019-02-27 00:13发布

Hello here it is the problem: when i get to the $_POST latin string strilen() works perfectly, but when i get cyrillic string strlen() doubles its value here is the code:

$word = $_POST['word'];
echo strlen($word) . '<br>'; //input: abc -> returns 3, input: абв -> returns 6 
var_dump($word); //input: abc -> returns string 'abc' (length=3), input: абв -> returns string 'абв' (length=6)

Do you have some ideas?!

3条回答
贼婆χ
2楼-- · 2019-02-27 00:46

strlen does not double anything, it simply reports what the situation is. Specifically, it reports how many bytes -- and not how many characters -- make up the string. That is because strlen does not have any knowledge of what a "character" is, and blindly assumes that 1 byte = 1 character. Therefore we say that "strlen is not multibyte-aware".

In your case, it seems that the browser submits UTF-8 encoded data to the server. In UTF-8, cyrillic is two bytes per character.

If you want to find out the number of characters in the string, use the multibyte-aware mb_strlen:

echo mb_strlen($word, 'UTF-8');
查看更多
Animai°情兽
3楼-- · 2019-02-27 00:47

if you want to get length in the terms of characters (not bytes) use a multi-byte version of strlen: mb_strlen: http://php.net/manual/en/function.mb-strlen.php

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-27 00:53

Try mb_strlen() if you're dealing with multi-byte characters.

http://php.net/manual/en/function.mb-strlen.php

查看更多
登录 后发表回答