Skip to content

Commit 8f8fa09

Browse files
committed
Merge pull request laravel#811 from xsbeats/feature/str_limit_exact
Feature: Str::limit_exact limits a string including its custom ending to a specified length
2 parents c7679ba + e9e8a5b commit 8f8fa09

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

laravel/documentation/strings.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ The **Str** class also provides three convenient methods for manipulating string
2525
#### Limiting the number of characters in a string:
2626

2727
echo Str::limit($string, 10);
28+
echo Str::limit_exact($string, 10);
2829

2930
#### Limiting the number of words in a string:
3031

laravel/str.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,31 @@ public static function limit($value, $limit = 100, $end = '...')
130130
return substr($value, 0, $limit).$end;
131131
}
132132

133+
/**
134+
* Limit the number of chracters in a string including custom ending
135+
*
136+
* <code>
137+
* // Returns "Taylor..."
138+
* echo Str::limit_exact('Taylor Otwell', 9);
139+
*
140+
* // Limit the number of characters and append a custom ending
141+
* echo Str::limit_exact('Taylor Otwell', 9, '---');
142+
* </code>
143+
*
144+
* @param string $value
145+
* @param int $limit
146+
* @param string $end
147+
* @return string
148+
*/
149+
public static function limit_exact($value, $limit = 100, $end = '...')
150+
{
151+
if (static::length($value) <= $limit) return $value;
152+
153+
$limit -= static::length($end);
154+
155+
return static::limit($value, $limit, $end);
156+
}
157+
133158
/**
134159
* Limit the number of words in a string.
135160
*

0 commit comments

Comments
 (0)