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


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

SENIOR FULL STACK SOFTWARE ENGINEER
Fort Worth, Texas
Filmsupply
PHP Web Developer
Orlando, FL
Christ for all Nations
PHP Developer
Manhattan, KS (open to Remote)
CivicPlus
Mid-Senior Laravel Developer
Exeter
Optix Solutions
Full Stack Web Developer
Las Vegas, NV
V Shred
Staff Software Engineer (Laravel)
Remote
smartbnb
Software Engineer (PHP, Laravel, Vue)
Los Angeles, CA
Relocity