比较两个字符串,如果其中一个较短,则返回另一个


Compare two strings, if one is shorter return that one

这个函数应该将字符串精简到给定的字符数或给定的单词数,以较短的数为限。如果它截断字符串,则在其后面附加一个"…"。

它工作,除了当我运行一个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 ? '' : '...');
}

我做错了什么?为什么在这种情况下它返回"…",但是在多单词的句子中它工作得很好?

问题是示例字符串中唯一的单词太长,因此您不将其添加到$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....