fbpx

Get first characters of a string in PHP

There are two primary ways to get the first characters of a string in PHP. For example, let’s say we have a description of an article but we want to trim it down to the first 30 characters to generate an excerpt.

Option 1: substr

To me, the easiest option is to use PHP’s substr function. Therefore, substr is my preferred method of getting the first characters of a string in PHP.

Per PHP’s documentation, the substr function allows you to return part of a string. The code example they provide is listed below:

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

So, in the function below, 0 is the position where you want to start from and 30 is the number of characters that you would like to show from the start of the string.

$first_part_of_string = substr($string,0,30);

For example, in order to get the first 30 characters of our article description, we would run the following code. As you see below, I prefer to trim the description before running it through substr so that the result won’t have spaces at the beginning or end and I want to add an ellipsis at the end so my users know that there is more to read:

$description = 'This article is all about getting the first part of a string in PHP. We show you different PHP functions that get you there as quickly as possible. ';

$excerpt = substr(trim($description),0,30).'...';

// this generates the following string - This article is all about gett...
echo $excerpt;

Option 2: mb_strimwidth

A second way to return the first characters of a string in PHP is to use the mb_strimwidth function. This is listed as the second option because I don’t use it as regularly as I use the substr when I code, but it’s just as easy to use.

Per PHP’s documentation, the mb_strimwidth function allows you to get a truncated string with a specified width. A code example that they provide is visible below:

mb_strimwidth ( string $str , int $start , int $width [, string $trimmarker = "" [, string $encoding = mb_internal_encoding() ]] ) : string

In order to go from the start of the string to the following 30 characters, you need to replace int $start with 0 and replace int $width with 30. This looks like the following function:

$first_part_of_string = mb_strimwidth($string, 0, 30, '...');

For our specific example, we want to return the excerpt of an article description. Again, I use the trim function to trim spaces from the beginning or end of the returned string and I use an ellipsis to show my users that there is more to read.

$description = 'This article is all about getting the first part of a string in PHP. We show you different PHP functions that get you there as quickly as possible. ';

$excerpt = mb_strimwidth(trim($description), 0, 30).'...';

// this generates the following string - This article is all about gett...
echo $excerpt;

Leave a Reply

Your email address will not be published. Required fields are marked *