* The 'truncate' modifier truncates a string.
*
* Usage:
- * {$foo|truncate:35:'...'}
+ * {$foo|truncate:35:' and more'}
*
* @author Marcel Werk
* @copyright 2001-2011 WoltLab GmbH
public function execute($tagArgs, TemplateEngine $tplObj) {
// default values
$length = 80;
- $etc = '...';
+ $etc = '…';
$breakWords = false;
// get values
if (isset($tagArgs[2])) $etc = $tagArgs[2];
if (isset($tagArgs[3])) $breakWords = $tagArgs[3];
- // execute plugin
- if ($length == 0) {
- return '';
- }
-
- if (StringUtil::length($string) > $length) {
- $length -= StringUtil::length($etc);
-
- if (!$breakWords) {
- $string = preg_replace('/\s+?(\S+)?$/', '', StringUtil::substring($string, 0, $length + 1));
- }
-
- return StringUtil::substring($string, 0, $length).$etc;
- }
- else {
- return $string;
- }
+ return StringUtil::truncate($string, $length, $etc, $breakWords);
}
}
return true;
}
+ /**
+ * Truncates the given string to a certain number of characters.
+ *
+ * @param string $string
+ * @param integer $length
+ * @param string $etc string to append when $string is truncated
+ * @param boolean $breakWords should words be broken in the middle
+ * @return string truncated string
+ */
+ public static function truncate($string, $length = 80, $etc = '…', $breakWords = false) {
+ if ($length == 0) {
+ return '';
+ }
+
+ if (self::length($string) > $length) {
+ $length -= self::length($etc);
+
+ if (!$breakWords) {
+ $string = preg_replace('/\\s+?(\\S+)?$/', '', self::substring($string, 0, $length + 1));
+ }
+
+ return self::substring($string, 0, $length).$etc;
+ }
+ else {
+ return $string;
+ }
+ }
+
/**
* Splits given string into smaller chunks.
*