Browse Source

Adds limit_exact method which will limit a string and its custom ending to a specified length

Signed-off-by: Jason Walton <jwalton512@gmail.com>
Jason Walton 12 years ago
parent
commit
e9e8a5b32e
2 changed files with 26 additions and 0 deletions
  1. 1 0
      laravel/documentation/strings.md
  2. 25 0
      laravel/str.php

+ 1 - 0
laravel/documentation/strings.md

@@ -25,6 +25,7 @@ The **Str** class also provides three convenient methods for manipulating string
 #### Limiting the number of characters in a string:
 #### Limiting the number of characters in a string:
 
 
 	echo Str::limit($string, 10);
 	echo Str::limit($string, 10);
+	echo Str::limit_exact($string, 10);
 
 
 #### Limiting the number of words in a string:
 #### Limiting the number of words in a string:
 
 

+ 25 - 0
laravel/str.php

@@ -130,6 +130,31 @@ class Str {
 		return substr($value, 0, $limit).$end;
 		return substr($value, 0, $limit).$end;
 	}
 	}
 
 
+	/**
+	 * Limit the number of chracters in a string including custom ending
+	 * 
+	 * <code>
+	 *		// 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, '---');
+	 * </code>
+	 * 
+	 * @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.
 	 * Limit the number of words in a string.
 	 *
 	 *