Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
user3932710 Avatar asked Sep 01 '14 06:09

user3932710


People also ask

How do you strlen in PHP?

PHP strlen() Function It calculates the length of the string including all the whitespaces and special characters. Syntax: strlen($string); Parameters: The strlen() function accepts only one parameter $string which is mandatory.

What is the use of the strlen function in PHP?

The strlen() function is used to get the string length. It returns the length of the string on success. If the string is empty, 0 is returned.

Is strlen thread safe?

The strlen() function is thread-safe.

How long is a string in PHP?

You can simply use the PHP strlen() function to get the length of a string. The strlen() function return the length of the string on success, and 0 if the string is empty.


1 Answers

Use mb_strlen

Returns the number of characters in string str having character encoding (the second parameter) encoding. A multi-byte character is counted as 1.

Since your 3 characters are all multi-byte, you get 6 returned with strlen, but this returns 3 as expected.

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

Fiddle

Note

It's important not to underestimate the power of this method and any similar alternatives. For example one could be inclined to say ok if the characters are multi-byte then just get the length with strlen and divide it by 2 but that will only work if all characters of your string are multi-byte and even a period . will invalidate the count. For example this

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

Returns 4 which is correct. So this function is not only taking the whole length and dividing it by 2, it counts 1 for every multi-byte character and 1 for every single-byte character.

Note2:

It looks like you decided not to use this method because mbstring extension is not enabled by default for old PHP versions and you might have decided not to try enabling it:) For future readers though, it is not difficult and its advisable to enable it if you are dealing with multi-byte characters as its not only the length that you might need to deal with. See Manual

like image 137
Hanky Panky Avatar answered Sep 21 '22 19:09

Hanky Panky