How to Get the First Several Characters of a String in PHP

  1. Using the substr() Function
  2. Using the mb_substr Function:
    1. Describing the substr Function

There are cases when you need to get the first several characters of a string. From first sight, it can seem to be an easy job. However, while working with multiple-byte string, problems may occur. Below, we will consider solutions on how to do that in the case of single-byte and multiple-byte strings.

Using the substr() Function

For single-byte strings, it is necessary to use the substr() function.

 substr ( string $string , int $start [, int $length ] ) : string

As the first argument, the function gets the string whose sub you want to take. As the second argument, it mentions the position, which the sub should start from. If there is a third argument, it specifies the number of the characters inside the string, otherwise, all the existing characters are returned. To be more precise, let’s consider an example:

// singlebyte strings 
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 1);  // bcdef

Using the mb_substr Function:

For multi-byte strings, it is recommended to use the mb_substr function.

mb_substr ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_encoding() ]] ) : string

The arguments operate in the same way as it was explained in the section above. Here is an example:

// multibyte strings 
echo mb_substr('եիաև', 1, 3);  // իաև
echo mb_substr('եիաև', 0, 4);  // եիաև
echo mb_substr('եիաև', 1);  // իաև
If you are not sure that the string is single-byte, then you can use the mb_substr function. It works for both cases.

Describing the substr Function

This PHP function is aimed at returning the portion of a string, indicated by the length and start parameters.

Once it is TRUE, then it returns the extracted part of the string. In the case of a failure it returns FALSE or an empty string.

For more information and options of using the substr function, you can follow this link.


Do you find this helpful?

Related articles