public function cropString($str, $len) {
if ( mb_strlen($str) <= $len ) {
return $str;
}
// find the longest possible match
$pos = 0;
foreach ( array('. ', '? ', '! ') as $punct ) {
$npos = mb_strrpos($str, $punct);
if ( $npos > $pos && $npos < $len ) {
$pos = $npos;
}
}
if ( !$pos ) {
// substr $len-3, because the ellipsis adds 3 chars
return mb_substr($str, 0, $len-3, 'UTF-8') . '...';
}
else {
// $pos+1 to grab punctuation mark
return mb_substr($str, 0, $pos+1, 'UTF-8');
}
}
No comments:
Post a Comment