From ba4fd3fab00123ecd92871870d0af5730748d34e Mon Sep 17 00:00:00 2001 From: Eric Barnes Date: Sun, 9 Oct 2011 23:23:45 -0400 Subject: [PATCH] Added str::limit and str::limit_words. Unfortunately php doesn't include mb_str_word_count. --- laravel/str.php | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/laravel/str.php b/laravel/str.php index 10066696..b01d397b 100644 --- a/laravel/str.php +++ b/laravel/str.php @@ -98,6 +98,55 @@ public static function length($value) return strlen($value); } + /** + * Limit the number of chars in a string + * + * + * // Limit the characters + * echo Str::limit_chars('taylor otwell', 3); + * results in 'tay...' + * + * + * @param string $value + * @param int $length + * @param string $end + * @return string + */ + public static function limit($value, $length = 100, $end = '...') + { + if (static::length($value) <= $length) return $value; + + if (function_exists('mb_substr')) + { + return mb_substr($value, 0, $length).$end; + } + + return substr($value, 0, $length).$end; + } + + /** + * Limit the number of words in a string + * + * + * // Limit the words + * echo Str::limit_chars('This is a sentence.', 3); + * results in 'This is a...' + * + * + * @param string $value + * @param int $length + * @param string $end + * @return string + */ + public static function limit_words($value, $length = 100, $end = '...') + { + $count = str_word_count($value,1); + + if ($count <= $length) return $value; + + return implode(' ',array_slice($count,0,$length)).$end; + } + /** * Convert a string to 7-bit ASCII. *