1 <?php
2 /**
3 * Smarty plugin
4 *
5 * @package Smarty
6 * @subpackage PluginsModifier
7 */
9 /**
10 * Smarty truncate modifier plugin
11 *
12 * Type: modifier<br>
13 * Name: truncate<br>
14 * Purpose: Truncate a string to a certain length if necessary,
15 * optionally splitting in the middle of a word, and
16 * appending the $etc string or inserting $etc into the middle.
17 *
18 * @link http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual)
19 * @author Monte Ohrt <monte at ohrt dot com>
20 * @param string $string input string
21 * @param integer $length lenght of truncated text
22 * @param string $etc end string
23 * @param boolean $break_words truncate at word boundary
24 * @param boolean $middle truncate in the middle of text
25 * @return string truncated string
26 */
27 function smarty_modifier_truncate($string, $length = 80, $etc = '...',
28 $break_words = false, $middle = false)
29 {
30 if ($length == 0)
31 return '';
33 if (is_callable('mb_strlen')) {
34 if (mb_detect_encoding($string, 'UTF-8, ISO-8859-1') === 'UTF-8') {
35 // $string has utf-8 encoding
36 if (mb_strlen($string) > $length) {
37 $length -= min($length, mb_strlen($etc));
38 if (!$break_words && !$middle) {
39 $string = preg_replace('/\s+?(\S+)?$/u', '', mb_substr($string, 0, $length + 1));
40 }
41 if (!$middle) {
42 return mb_substr($string, 0, $length) . $etc;
43 } else {
44 return mb_substr($string, 0, $length / 2) . $etc . mb_substr($string, - $length / 2);
45 }
46 } else {
47 return $string;
48 }
49 }
50 }
51 // $string has no utf-8 encoding
52 if (strlen($string) > $length) {
53 $length -= min($length, strlen($etc));
54 if (!$break_words && !$middle) {
55 $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
56 }
57 if (!$middle) {
58 return substr($string, 0, $length) . $etc;
59 } else {
60 return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
61 }
62 } else {
63 return $string;
64 }
65 }
67 ?>