这个函数应该将一个字符串修剪为给定的字符数或给定的字数,更短的。如果它截断字符串,则在其上附加“...”。
除非我使用像字符串这样的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 ? '' : '...');
}
我做错了什么?为什么在这种情况下它会返回“...”,但在多字句中它可以正常工作?
答案 0 :(得分:0)
问题是示例字符串中唯一的单词太长,因此您不会将其添加到$truncated
数组中。
你可以考虑这个:
if ($chars > $maxChars) {
if (!$truncated) { // no captured words yet, add as much as possible
$truncated[] = substr($fragment, 0, $maxChars - $chars);
}
break;
}
如果您还没有任何捕获的单词,它会复制该单词,直到它完全填满$maxChars
。输出:
https://accounts.google.com/SignUp?service=youtube&continue=http%3A%2F%2Fwww.youtube....