我做的这个函数看起来很整洁:
function truncate($input, $maxWords, $maxChars)
{
$words = preg_split('/\s+/', $input);
$words = array_slice($words, 0, $maxWords);
$words = array_reverse($words);
$chars = 0;
$truncated = array();
while(count($words) > 0)
{
$fragment = trim(array_pop($words));
$chars += strlen($fragment);
if($chars > $maxChars) break;
$truncated[] = $fragment;
}
$result = implode($truncated, ' ');
if ($input == $result)
{
return $input;
}
else
{
return preg_replace('/[^\w]$/', '', $result) . '...';
}
}
一些测试:
$str = 'The quick brown fox jumped over the lazy dog';
echo truncate($str, 5, 42); // The quick brown fox jumped...
echo truncate($str, 3, 42); // The quick brown...
echo truncate($str, 50, 30); // The quick brown fox jumped over the...
echo truncate($str, 50, 100); // The quick brown fox jumped over the lazy dog
它也不会将单词减半,因此如果某个单词的字符数超过了提供的限制,它将被忽略。