Search code examples
phpstringdoublestrlen

Php length of cyrillic string doubles its value


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?!


Solution

  • 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');