如果我在 PHP 中有一个字符串,它在 PHP 中是令人讨厌的长字符串,我想缩短它然后向其附加一些内容。
我想将它缩短到前 6 个单词或 42 个字符,无论哪个更短,然后在它被缩短的情况下附加一个“...”。
唯一不会缩短并且不添加“...”的情况是它最初少于 6 个单词或 42 个字符。
我如何在 PHP 中执行此操作?
从逻辑上讲,我认为我会用空格拆分字符串,然后将每个内容添加到数组中的空格之前,只从该数组中取出前 6 个元素并将它们写入新字符串。
这是我目前的代码:
str_1 = 'The quick brown fox jumped over the lazy dog';
$words = explode(" ", $str_1);
$counter = 0;
str_2 = '';
foreach($words as $word){
if($counter < 5){
//append $words[counter] to str_2;
counter++;
}
else{
break;
}
}
我不知道如何进行字符计数、比较或追加。
有没有人有什么想法?
最佳答案
我做的这个函数看起来很整洁:
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, ' ');
if ($input == $result)
{
return $input;
}
else
{
return preg_replace('/[^\w]$/', '', $result) . '...';
}
}
一些测试:
$str = 'The quick brown fox jumped over the lazy dog';
echo truncate($str, 5, 42); // The quick brown fox jumped...
echo truncate($str, 3, 42); // The quick brown...
echo truncate($str, 50, 30); // The quick brown fox jumped over the...
echo truncate($str, 50, 100); // The quick brown fox jumped over the lazy dog
它也不会将单词减半,因此如果一个单词将字符数推到超过提供的限制,它将被忽略。
关于php - 将字符串限制为 PHP 中的前 5 个单词或前 42 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16725974/