Using str_limit to restrict a string to a certain length

Tutorials

October 8th, 2016

laravel-news-video.png

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:

1$value = str_limit('This string is really really long.', 7);
2
3// 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:

1$value = str_limit('This string is really really long.', 7, '&raquo');
2
3// 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:

1public static function limit($value, $limit = 100, $end = '...')
2{
3 if (mb_strwidth($value, 'UTF-8') <= $limit) {
4 return $value;
5 }
6
7 return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
8}

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:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.