From 17ea09364d5b9192fe0b9015ac328a4bb0e79325 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Sat, 15 Oct 2011 14:17:58 -0500 Subject: [PATCH] fixed str test cases and str::limit function. --- application/routes.php | 1 + laravel/str.php | 16 ++++++++-------- tests/Cases/StrTest.php | 4 ++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/application/routes.php b/application/routes.php index 56ea31be..ff11a9b9 100644 --- a/application/routes.php +++ b/application/routes.php @@ -39,6 +39,7 @@ 'GET /' => function() { + return Laravel\Str::limit('This is a string of text', 3, '...'); return View::make('home.index'); }, diff --git a/laravel/str.php b/laravel/str.php index 5f9b2d9a..8e64eb56 100644 --- a/laravel/str.php +++ b/laravel/str.php @@ -101,11 +101,8 @@ public static function length($value) /** * Limit the number of characters in a string. * - * Word integrity is preserved, so the number of characters in the - * truncated string will be rounded to the nearest word ending. - * * - * // Returns "Taylor..." + * // Returns "Tay..." * echo Str::limit('Taylor Otwell', 3); * * // Limit the number of characters and append a custom ending @@ -113,17 +110,20 @@ public static function length($value) * * * @param string $value - * @param int $length + * @param int $limit * @param string $end * @return string */ public static function limit($value, $limit = 100, $end = '...') { - if (static::length($value) < $limit) return $value; + if (static::length($value) <= $limit) return $value; - $limit = preg_replace('/\s+?(\S+)?$/', '', substr($value, 0, $limit)); + if (function_exists('mb_substr')) + { + return mb_substr($value, 0, $limit, Config::get('application.encoding')).$end; + } - return (static::length($limit) == static::length($value)) ? $value : $limit.$end; + return substr($value, 0, $limit).$end; } /** diff --git a/tests/Cases/StrTest.php b/tests/Cases/StrTest.php index 55b47830..c31cdee1 100644 --- a/tests/Cases/StrTest.php +++ b/tests/Cases/StrTest.php @@ -45,7 +45,7 @@ public function test_limit() public function test_limit_words() { - $this->assertEquals('This is a...', Laravel\Str::limit_words('This is a string of text', 3, '...')); - $this->assertEquals('This is a string ', Laravel\Str::limit_words('This is a string of text', 4, ' ')); + $this->assertEquals('This is a...', Laravel\Str::words('This is a string of text', 3, '...')); + $this->assertEquals('This is a string ', Laravel\Str::words('This is a string of text', 4, ' ')); } } \ No newline at end of file