Subversion Repositories ALCASAR

Rev

Details | Last modification | View Log

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