Common\Core\Twig\Extensions\BaseTwigModifiers::truncate PHP Method

truncate() public static method

Truncate a string syntax: {{ $string|truncate($max-length, $append-hellip, $closest-word) }}.
public static truncate ( string $string, integer $length, boolean $useHellip = true, boolean $closestWord = false ) : string
$string string The string passed from the template.
$length integer The maximum length of the truncated string.
$useHellip boolean Should a hellip be appended if the length exceeds the requested length?
$closestWord boolean Truncate on exact length or on closest word?
return string
    public static function truncate($string, $length, $useHellip = true, $closestWord = false)
    {
        // remove special chars, all of them, also the ones that shouldn't be there.
        $string = \SpoonFilter::htmlentitiesDecode($string, null, ENT_QUOTES);
        // remove HTML
        $string = strip_tags($string);
        // less characters
        if (mb_strlen($string) <= $length) {
            return \SpoonFilter::htmlspecialchars($string);
        } else {
            // more characters
            // hellip is seen as 1 char, so remove it from length
            if ($useHellip) {
                --$length;
            }
            // truncate
            if ($closestWord) {
                $string = mb_substr($string, 0, strrpos(substr($string, 0, $length + 1), ' '), 'UTF-8');
            } else {
                $string = mb_substr($string, 0, $length, 'UTF8');
            }
            // add hellip
            if ($useHellip) {
                $string .= '…';
            }
            // return
            return \SpoonFilter::htmlspecialchars($string, ENT_QUOTES);
        }
    }