2013-12-09 21 views
0

(PHP)可以使這個功能更緊湊嗎?我使用這個函數在主頁上撰寫文章摘要。它在文本的極限長度之後找到第一個空格,因爲避免了ex的單詞分隔。我的筆記本是好的 - >摘要:我的筆記本..它不應該是我的筆記...PHP - 這個過程更緊湊的功能?

function summary($posttext){ 
$limit = 60; 

$spacepos = @strpos($posttext," ",$limit); //error handle for the texts shorter then 60 ch 

while (!$spacepos){ 
$limit -= 10; //if text length shorter then 60 ch decrease the limit 
$spacepos = @strpos($postext," ",$limit); 
} 

$posttext = substr($posttext,0,$spacepos).".."; 

return $posttext; 
} 
+5

緊湊型或不是:考慮返回布爾型「假」(未找到)和整數「0」(位於0處)的strops之間的區別 –

+1

您真的不應該使用錯誤抑制字符('@')。這是不好的做法,會讓你自己更難調試。 –

+0

難道剛剛用TRIM包裝它嗎?他正在檢查一個空間,非常罕見,需要有一個空間作爲字符串的第一個字符。事實上,如果他們在進入數據庫的過程中清理乾淨,你所說的沒有多大意義。除非我誤解。 – Mattt

回答

0

我儘量不打破分割的話

function summary($posttext, $limit = 60){ 
    if(strlen($posttext) < $limit) { 
     return $posttext; 
    } 
    $offset = 0; 
    $split = explode(" ", $posttext); 
    for($x = 0; $x <= count($split); $x++){ 
     $word = $split[$x]; 
     $offset += strlen($word); 
     if(($offset + ($x + 1)) >= $limit) { 
      return substr($posttext, 0, $offset + $x) . '...'; 
     } 
    } 
    return $posttext; 
} 
+0

這個網址有幾個好主意。它看起來並不像這個內置函數,如果那是你想要的。 http://stackoverflow.com/questions/7348103/short-text-php – Viridis

0

像這樣的東西會在最後一個完整的單詞拆不打破這個詞。

function limit_text($text, $len) { 
     if (strlen($text) < $len) { 
      return $text; 
     } 
     $text_words = explode(' ', $text); 
     $out = null; 


     foreach ($text_words as $word) { 
      if ((strlen($word) > $len) && $out == null) { 

       return substr($word, 0, $len) . "..."; 
      } 
      if ((strlen($out) + strlen($word)) > $len) { 
       return $out . "..."; 
      } 
      $out.=" " . $word; 
     } 
     return $out; 
    } 
0

感謝根據您suggestions.And您helps.I糾正了我的代碼的最終版本是這樣的:

function summary($posttext){ 
$limit = 60; 

if (strlen($posttext)<$limit){ 

$posttext .= ".."; 

}else { 
$spacepos = strpos($posttext," ",$limit); 
$posttext = substr($posttext,0,$spacepos).".."; 
} 
return $posttext; 
}