Search code examples
phpstrlenmultibytepersian

How can I use strlen in php for Persian?


I have this code:

$string = 'علی';
echo strlen($string);

Since $string has 3 Persian characters, output must be 3 but I get 6.

علی has 3 characters. Why my output is 6 ?

How can I use strlen() in php for Persian with real output?


Solution

  • try this:

    function ustrlen($text)
    {
        if(function_exists('mb_strlen'))
            return mb_strlen( $text , 'utf-8' );
        return count(preg_split('//u', $text)) - 2;
    }
    

    it will work for any php version.