Skip to content

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. 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 substr() function.

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

php
// 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
<?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 mb_substr function.

Example of using mb_substr() function in PHP

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
<?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 substr function, you can visit this link.

Dual-run preview — compare with live Symfony routes.