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

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.

Watch a course Learn object oriented PHP

Using the substr() Function

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

substr(string $string, int $offset, ?int $length = null): 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:

<?php

// 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.

<?php

mb_substr(
    string $string,
    int $start,
    ?int $length = null,
    ?string $encoding = null
): string

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

<?php

// 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.