Truncating Text on Word Boundaries
<?php
function truncate_text_nicely($string, $max, $moretext) {
if (strlen($string) > $max) {
$max -= strlen($moretext);
$string = strrev(strstr(strrev(substr($string, 0, $max)), ' '));
$string .= $moretext;
}
return $string;
}
$str = 'This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.';
$values = truncate_text_nicely($str, 20, '...');
echo "<pre>{$values}</pre>";
?>
Related examples in the same category