我想出了这个函数,它将给定的字符串截断为给定的字数或给定的字符数,无论是更短的字符。 然后,在字符数或字数限制之后切断所有内容后,它会在字符串后附加一个“...”。
如何从字符串中间删除字符/单词并将其替换为“...”而不是用“...”替换末尾的字符/单词?
这是我的代码:
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){
if(!$truncated){
$truncated[]=substr($fragment, 0, $maxChars - $chars);
}
break;
}
$truncated[] = $fragment;
}
$result = implode($truncated, ' ');
return $result . ($input == $result ? '' : '...');
}
例如,如果调用truncate('the quick brown fox jumps over the lazy dog', 8, 16);
,则16个字符更短,因此将发生截断。因此,'狐狸跳过懒狗'将被删除,'...'将被追加。
但是,相反,我怎么能有一半的字符限制来自字符串的开头,一半来自字符串的结尾,中间删除的内容被'...'替换? 所以,我想要回来的字符串,其中一个案例是:'quic ...懒狗'。
答案 0 :(得分:25)
$text = 'the quick brown fox jumps over the lazy dog';
$textLength = strlen($text);
$maxChars = 16;
$result = substr_replace($text, '...', $maxChars/2, $textLength-$maxChars);
$结果现在是:
the quic...lazy dog
答案 1 :(得分:1)
这不会改变短于$maxChars
的输入,并会考虑替换...
的长度:
function str_truncate_middle($text, $maxChars = 25, $filler = '...')
{
$length = strlen($text);
$fillerLength = strlen($filler);
return ($length > $maxChars)
? substr_replace($text, $filler, ($maxChars - $fillerLength) / 2, $length - $maxChars + $fillerLength)
: $text;
}
答案 2 :(得分:0)
以下是我最终使用的内容:
/**
* Removes characters from the middle of the string to ensure it is no more
* than $maxLength characters long.
*
* Removed characters are replaced with "..."
*
* This method will give priority to the right-hand side of the string when
* data is truncated.
*
* @param $string
* @param $maxLength
* @return string
*/
function truncateMiddle($string, $maxLength)
{
// Early exit if no truncation necessary
if (strlen($string) <= $maxLength) return $string;
$numRightChars = ceil($maxLength / 2);
$numLeftChars = floor($maxLength / 2) - 3; // to accommodate the "..."
return sprintf("%s...%s", substr($string, 0, $numLeftChars), substr($string, 0 - $numRightChars));
}
对于我的用例,字符串的右侧包含更多有用的信息,因此这种方法偏向于从左半部分中取出字符。