This simple view helper for the Zend Framework will truncate a
string to the desired length and automatically add customizable
postfixes if the string was truncated.
Usage Example
This view helper is based on “normal” PHP<?php echo $this->truncate($text, $length, array('ending'=>'..', 'exact'=>false)) ?>
After truncated string will look like this<p>This is my long string which needs to be truncated..</p>
Due to the fact that 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!<?php
class My_View_Helper_Text_Truncate extends Zend_View_Helper_Abstract
{
public function truncate($text, $length = 100, $options = array())
{
$default = array(
'ending' => '...', 'exact' => false
);
$options = array_merge($default, $options);
extract($options);
if (mb_strlen($text) <= $length) {
return $text;
} else {
$truncate = mb_substr($text, 0, $length - mb_strlen($ending));
}
if (!$exact) {
$spacepos = mb_strrpos($truncate, ' ');
if (isset($spacepos)) {
$truncate = mb_substr($truncate, 0, $spacepos);
}
}
$truncate .= $ending;
return $truncate;
}
}
Download View Helper
No comments:
Post a Comment