Login with OpenID

"Truncate" View Helper for the Zend Framework

Written by Hector Virgen
Published on June 2, 2009

This simple view helper for the Zend Framework will truncate a string to the desired length and automatically add customizable prefixes and postfixes if the string was truncated.

Usage Example

This view helper works similarly to substr, with two additional parameters for specifying the prefix and postfix.

 
<h1>My Truncated Blog Post</h1>
<p><?= $this->truncate($this->blog, 0, 40, '', '... [more]') ?></p>

If your blog post was very long (like this one), the result would be something like this:

 
<h1>My Truncated Blog Post</h1>
<p>This simple view helper for the Zend Fra... [more]</p>

Due to the fact this this helper works on the string directly, you may need to strip html tags first if your string is HTML, otherwise you will end up with a lot of broken tags!

Class: Virgen_View_Helper_Truncate

 
<?php
 
class Virgen_View_Helper_Truncate
{
    public function truncate($string, $start = 0, $length = 100, $prefix = '...', $postfix = '...')
    {
        $truncated = trim($string);
        $start = (int) $start;
        $length = (int) $length;
        
        // Return original string if max length is 0
        if ($length < 1) return $truncated;
        
        $full_length = iconv_strlen($truncated);
        
        // Truncate if necessary
        if ($full_length > $length) {
            // Right-clipped
            if ($length + $start > $full_length) {
                $start = $full_length - $length;
                $postfix = '';
            }
            
            // Left-clipped
            if ($start == 0) $prefix = '';
            
            // Do truncate!
            $truncated = $prefix . trim(substr($truncated, $start, $length)) . $postfix;
        }
        
        return $truncated;
    }
}

Comments

blog comments powered by Disqus