Using str_limit to restrict a string to a certain length
Published on by Eric L. Barnes
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, '»'); // 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.
Eric is the creator of Laravel News and has been covering Laravel since 2012.