此函数应该将字符串修剪为给定的字符数或给定的单词数,无论哪个更短。如果它截断了字符串,请在其上附加一个“...”。
它可以工作,除非我使用字符串之类的 URL 运行它,然后它只返回“...”本身。
例如:
truncate('https://accounts.google.com/SignUp?service=youtube&continue=http%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26feature%3Dplaylist%26hl%3Den_US%26next%3D%252Faccount_recovery%26nomobiletemp%3D1', 1, 85);
这是功能:
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, ' ');
return $result . ($input == $result ? '' : '...');
}
我究竟做错了什么?为什么在这种情况下它返回“...”,但在多词句子中它工作正常?