Laravel String Helper Function: substr

November 16, 2016 —John Koster

The substr helper method is a convenient helper built on top of PHP's mb_substr function (unlike PHP's mb_substr function, substr does not provide a way to change the encoding that is used) that is used to return a portion of a string. The substr method defines two required parameters ($string and $start) and one optional parameter ($length).

The signature for the substr helper function is:

substr($string, $start, $length = null)

An argument supplied for $string must be the string that you want to return a portion of. $start is used to determine where the substring starts (all positions start at 0). If the $start is positive, the substring will start at the supplied position from the start of the string. If $start is negative, the substring will start at the supplied position from the end of the string. The $length is used to determine how the long the returned substring will be (in other words, how many characters are allowed in the returned substring). If $length is null, the substring will continue on to the end of the string.

substr Encoding

PHP's mb_substr function allows you to change the encoding that is used when extracting the substring from the string. Laravel's substr helper method always uses the UTF-8 encoding when making its call to the mb_substr function.

The following examples highlight the usage of the substr helper method. An example string of 01213456789 will be used so that the substring will be easier to identify. The results of the function call will appear above the call as a comment.

1use Illuminate\Support\Str;
2 
3// Create a testing string.
4$testString = '0123456789';
5 
6// 56789
7Str::substr($testString, 5);
8 
9// 6789
10Str::substr($testString, 6);
11 
12// 67
13Str::substr($testString, 6, 2);
14 
15// 89
16Str::substr($testString, -2);
17 
18// 8
19Str::substr($testString, -2, 1);

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.