note 35476 deleted from function.wordwrap by aidan
| From: | aidan@php.net | Date: | Mon, 19 Jul 2004 23:26:01 +0000 |
| Subject: | note 35476 deleted from function.wordwrap by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-73649@lists.php.net to get a copy of this message | ||
Note Submitter: andy@tagish.com
----
Neotropic's sentence truncating code is a little ineffecient - there's no need to chop the
sentence into words or indeed chop the words into characters to find out how long they are. This
does the trick a little more succinctly I think:
function truncate($str, $len, $el = '...')
{
if (strlen($str) > $len) {
$xl = strlen($el);
if ($len < $xl) {
return substr($str, 0, $len);
}
$str = substr($str, 0, $len-$xl);
$spc = strrpos($str, ' ');
if ($spc > 0) {
$str = substr($str, 0, $spc);
}
return $str . $el;
}
return $str;
}