API16

API16:JHtmlString/truncate

From Joomla! Documentation

Revision as of 21:48, 16 February 2011 by Dextercowley (talk | contribs) (fix incorrect importing section)

Description

Truncates text blocks over the specified character limit. The behavior will not truncate an individual word, it will find the first space that is within the limit and truncate at that point. This method is UTF-8 safe.

[Edit Descripton]

Template:Description:JHtmlString/truncate

Syntax

truncate($text, $length=0)
Parameter Name Default Value Description
$text $text The text to truncate.
$length 0 $length The maximum length of the text.

Returns

string The truncated text.

Defined in

libraries/joomla/html/html/string.php

Importing

JLoader::register('JHtmlString', JPATH_LIBRARIES.'/joomla/html/html/string.php');

Source Body

function truncate($text, $length = 0)
{
        // Truncate the item text if it is too long.
        if ($length > 0 && JString::strlen($text) > $length)
        {
                // Find the first space within the allowed length.
                $tmp = JString::substr($text, 0, $length);
                $tmp = JString::substr($tmp, 0, JString::strrpos($tmp, ' '));

                // If we don't have 3 characters of room, go to the second space within the limit.
                if (JString::strlen($tmp) >= $length - 3) {
                        $tmp = JString::substr($tmp, 0, JString::strrpos($tmp, ' '));
                }

                $text = $tmp.'...';
        }

        return $text;
}

[Edit See Also] Template:SeeAlso:JHtmlString/truncate

Examples

echo JHTML::_('string.truncate', ($this->item->title), $params->get('readmore_limit'));

<CodeExamplesForm />