<?php
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){
if(!$truncated){
$truncated[]=substr($fragment, 0, $maxChars - $chars);
}
break;
}
$truncated[] = $fragment;
}
$result = implode($truncated, ' ');
$wordCount = count($truncated);
// Handle Case where character count is violated
if ($maxLength && $chars > $maxLength){
$result = substr($result, 0, ceil($maxLength/2)."...".substr($results, -1 * floor($maxLength/2));
} elseif($wordCount && $wordCount > $maxWords){
// deal with too many words
$result = implode(" ", array_slice($truncated, 0, ceil($wordCount/2))." ... ".
implode(" ", array_slice($truncated, $wordCount - floor($wordCount/2) -1))
}
return $result;
}
$thing = truncate('the quick brown fox jumped over the lazy dog', 8, 16);
echo $thing;
- Output for 5.3.0 - 5.3.24, 5.4.0 - 5.4.15
- Parse error: syntax error, unexpected ';' in 3Wiei on line 31
Process exited with code 255. - Output for 5.3.25
- Parse error: syntax error, unexpected ';' in /in/3Wiei on line 31
Process exited with code 255.
preferences:
175.38 ms | 1386 KiB | 49 Q