diff --git a/laravel/documentation/strings.md b/laravel/documentation/strings.md index 002d9148..4164e5ec 100644 --- a/laravel/documentation/strings.md +++ b/laravel/documentation/strings.md @@ -25,6 +25,7 @@ ## Word & Character Limiting #### Limiting the number of characters in a string: echo Str::limit($string, 10); + echo Str::limit_exact($string, 10); #### Limiting the number of words in a string: diff --git a/laravel/str.php b/laravel/str.php index 964b5d5b..23f2b731 100644 --- a/laravel/str.php +++ b/laravel/str.php @@ -130,6 +130,31 @@ public static function limit($value, $limit = 100, $end = '...') return substr($value, 0, $limit).$end; } + /** + * Limit the number of chracters in a string including custom ending + * + * + * // Returns "Taylor..." + * echo Str::limit_exact('Taylor Otwell', 9); + * + * // Limit the number of characters and append a custom ending + * echo Str::limit_exact('Taylor Otwell', 9, '---'); + * + * + * @param string $value + * @param int $limit + * @param string $end + * @return string + */ + public static function limit_exact($value, $limit = 100, $end = '...') + { + if (static::length($value) <= $limit) return $value; + + $limit -= static::length($end); + + return static::limit($value, $limit, $end); + } + /** * Limit the number of words in a string. *