2013-06-01 65 views
8

我想出了這個函數,將給定的字符串截斷爲給定數量的字或給定數量的字符無論更短。 然後,在字符或單詞數量限制後切斷所有內容後,它會在該字符串中附加'...'。截斷字符串,但刪除中間的字符串,而不是結束

如何從字符串中間刪除字符/單詞,並用'...'替換它們,而不是用'...'替換最後的字符/單詞?

這裏是我的代碼:

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 ...懶狗'。

回答

21
$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簡潔,美觀。 – Orangepill

+3

需要'if($ textLength> $ maxChars)' – Petah

+1

請注意,即使$ maxChars設置爲16,這也會產生19個字符的字符串。 – adean

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)); 
} 

對於我的使用情況下,字符串的右側含有更多的有用信息,從而這種方法偏向於將字符從左半部分中取出。

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; 
}