Creating a Zend Framework View Helper to Truncate Text

Written by James Mansson on December 11, 2013 Categories: Zend Framework 1

It is sometimes useful to be able to truncate a longer piece of text to fit into the available space, such as when displaying a series of search results. There are a number of ways to do this; one good one for PHP is described in this Stack Overflow answer.

If you are using Zend Framework 1, this code could be wrapped up in a view helper as follows:

<?php
class Application_View_Helper_TruncatedText extends Zend_View_Helper_Abstract
{
    /**
     * Truncate a string only at a whitespace
     * 
     * @param string $text The string to truncate
     * @param intger $length The length to truncate to
     * @return string
     */
    public function truncatedText($text, $length)
    {
        $length = abs((int)$length);

        if (strlen($text) > $length)
        {
            $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
        }

        return($text);
    }
}

You can now access this from your view scripts, or wherever you have access to a view object.

No Comments on Creating a Zend Framework View Helper to Truncate Text

Leave a Reply

Your email address will not be published. Required fields are marked *