W3docs

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

On this page, we represent to you the ways of getting the first five characters of a string in PHP. Keep on reading the snippet and check out the examples.

There are cases when you need to get the first several characters of a string. At first glance, it may seem like an easy task. However, when working with multi-byte strings, problems may occur. Below, we will consider solutions on how to do that in the case of single-byte and multi-byte strings.

Using the substr() Function

For single-byte strings, it is necessary to use the <kbd class="highlighted">substr()</kbd> function.

Example of using substr() function to get the first several characters of a PHP string

// substr(string $string, int $offset, ?int $length = null): string

As the first argument, the function takes the string from which you want to extract a substring. The second argument specifies the starting position. If a third argument is provided, it defines the number of characters to return; otherwise, all remaining characters are returned. To be more precise, let’s consider an example:

php substr

<?php

// single-byte 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 <kbd class="highlighted">mb_substr</kbd> function.

Example of using mb_substr() function in PHP

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

The arguments work the same way as explained above. Here is an example:

php mb_substr

<?php

// multi-byte strings
echo mb_substr('եիաև', 1, 3); // իաև
echo mb_substr('եիաև', 0, 4); // եիաև
echo mb_substr('եիաև', 1); // իաև

?>
Note

Ensure your script file is saved as UTF-8 to guarantee correct rendering of multi-byte characters.

Info

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.

On success, the function returns the extracted substring. On failure, it returns FALSE or an empty string.

For more information and options of using the <kbd class="highlighted">substr</kbd> function, you can visit this link.