Using str_limit to restrict a string to a certain length

Using str_limit to restrict a string to a certain length

When building for the web, there are many different ways to limit a string. For example, you could use CSS, JavaScript, or do it through PHP.

Limiting strings is such a common use case that Laravel provides a simple helper to make this easy and I’ve recorded a short video to give you an example walkthrough:

The str_limit is autoloaded and available in both your application code and your views. Here is a simple example demonstrating the default use case. The first parameter is your string and the second is the length you want to trim it too. In this situation seven characters:

$value = str_limit('This string is really really long.', 7);

// This st...

This helper also includes a third parameter so you change the ending on the trimmed string. For instance, pretend you want to have an arrow instead of three dots. That can be setup like this:

$value = str_limit('This string is really really long.', 7, '&raquo');

// This st»

If you want to learn more about this helper look at the Illuminate\Support\Str class which is where the underlying code is:

public static function limit($value, $limit = 100, $end = '...')
{
    if (mb_strwidth($value, 'UTF-8') <= $limit) {
        return $value;
    }

    return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
}

The first if checks to see if the string is less than the limit using the Multi-Byte mb_strwidth PHP function. Finally, it does a right trim and the Multi-Byte mb_strimwidth to truncate the string to a specific length.

Filed in: Laravel Tutorials / Helpers / Video
Laravel News Partners

Laravel Jobs

Medior Laravel Backend Developer (The Netherlands/Dutch only)
Nijmegen, The Netherlands
BigSpark B.V.
Laravel Developer
Remote
Enjin
Senior Laravel Backend Engineer
Remote, USA Only
Kittyhawk.io, Inc.
Full Stack Developer
Rijssen
CODE14
Senior PHP Developer
Remote
ProjectMark

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.