This function is supposed to trim down a string to the given number of characters or the given number of words, what ever is shorter. And if it truncates the string, append a "..." to it.
It works except when I run it with a URL like string, then it just returns the "..." by itself.
For example:
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);
Here is the function:
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 ? '' : '...');
}
What am I doing wrong? Why does it return "..." in this case, but in multi-word sentences it works fine?