How can I use strlen in php for persian?

I have this code:

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

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

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

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

+7
php multibyte strlen persian
source share
5 answers

try the following:

 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.

+6
source share

Use mb_strlen

Returns the number of characters in str string that have character encoding (second parameter). A multibyte character is considered equal to 1.

Since your 3 characters are multibyte, you get 6 returned with strlen , but that returns 3 as expected.

 echo mb_strlen($string,'utf-8'); 

Fiddle

Note

It is important not to underestimate the power of this method and any such alternatives. For example, one could say “good” if the characters are multi-byte, and then just get the length using strlen and divide it by 2, but this will only work if all the characters in your string are multi-byte and even period . will invalidate the account. For example, this

 echo mb_strlen('علی.','utf-8'); 

Returns 4 , which is correct. Thus, this function not only takes the entire length and divides it by 2, it takes into account 1 for each multi-byte character and 1 for each single-byte character.

Note2:

It seems that you decided not to use this method, because the mbstring is not used by default for older versions of PHP, and you may have decided not to try to enable it :) For future readers, this is not difficult, and it is recommended to include it if you are dealing with multibyte characters, as this is not only the length with which you may be required. See manual

+13
source share

mb_strlen function is your friend

+5
source share
 $string = 'علی'; echo mb_strlen($string, 'utf8'); 
+4
source share

Starting with PHP5, iconv_strlen() can be used (as described in php.net, it returns the number of characters of a string, so this is probably the best choice):

 iconv_strlen("علی"); // 3 

Based on this answer from chernyshevsky@hotmail.com , you can try the following:

 function string_length (string $string) : int { return strlen(utf8_decode($string)); } string_length("علی"); // 3 

As well as others, you can use mb_strlen() :

 mb_strlen("علی"); // 3 
  • There are very few differences between them (for illegal Latin characters):

     iconv_strlen("a\xCC\r"); // A notice string_length("a\xCC\r"); // 3 mb_strlen("a\xCC\r"); // 2 
  • Performance: mb_strlen () is the fastest. In general, there is no difference between iconv_strlen () and string_length () in performance. But it is amazing that mb_strlen () is faster than about 9 times (as I tested)!

Note. Add "echo" to each expression to output them !;)

0
source share

All Articles