Monday, 13 August 2018

How to Get/check the Length of a String Correctly in PHP?

Problem:

You have a string and you want to find out the number of characters in a string.

Solution:

You can get the length of a string using any of the following two ways-

Method 1: Using strlen() function

Getting the length of a string using strlen() function may seem very easy at first. But, there is a catch in this method.
When considering a string, the strlen() function counts the bytes, not the characters. The problem is all character encoding systems don’t use one byte to represent one character. For example, in ISO-8859-1 encoding system, which is the default source encoding system, uses 1 byte to represent 1 character. On the other hand, UTF-8, which is the widely used encoding system, may take upto 4 bytes to represent 1 character.
So, to get the length of a string using strlen, we’ll follow 2 steps-
  1. Convert the string to single byte ISO-8859-1 using utf8_decode() function assuming that the string is encoded with UTF-8.
  2. Then, find out the length of the of the string using strlen() function

See the example below-
1
2
3
4
5
<?php
$string = "HallÄ";
$length = strlen( utf8_decode( $string ) );
echo "The length of the string is: " . $length;
?>
Output:
The length of the string is: 5

Method 2: Using mb_strlen() function

mb_strlen() function also returns the length of the string. The benefit of using mb_strlen() function is that it considers multi-byte character as 1.
See the example below –
1
2
3
4
5
<?php
$string = "HallÄ";
$length = mb_strlen($string, 'utf-8');
echo "The length of the string is: " . $length;
?>
Output:
The length of the string is: 5

0 comments:

Post a Comment