2014-04-21 116 views
0

我有以下代碼,並且只需要在描述中回顯出100個或更少的字,而不是整個描述。無論如何,通過編輯這段代碼來做到這一點?PHP描述摘要

public static function getExcerpt($profile) { 
    $out=''; 
    if(!empty($profile['description'])) { 
     $out.=$profile['description'].' '.__('', 'lovestory'); 
    } 

    return $out; 
} 

謝謝!

+0

存在。我建議你看看php文檔,特別是字符串搜索函數:你正在尋找一種方法來搜索字符串中第100個空白字符的發生。 – arkascha

回答

2
// for 100 characters... 
if (strlen($profile['description']) > 100) 
    $description = substr($profile['description'], 0, 100) . "..."; 
else 
    $description = $profile['description']; 

$out.= $description . ' ' . __('', 'lovestory'); 


// for 100 words 
$out.= implode(" ", array_slice(explode(" ", $profile['description']), 0, 100)) .' '.__('', 'lovestory'); 
+0

那隻會輸出前100個字符? –

+0

是的,它只會輸出前100個字符,你想要前100個字嗎?如果是,那麼只需用「」(空間)爆炸它,並且只用空間爆炸數百個。 –

+0

是的,他在他的問題中說'話':D –

0

您可以使用一個空的空間爆炸產生的話數組,如果有超過100個字,使用array_slice選擇第一個100,然後破滅數組轉換回字符串

$words = explode(' ', $out); 
if(count($words) > 100){ 
    return implode(' ', array_slice($words, 0, 100)); 
else{ 
    return $out; 
} 
0

這取決於你想如何準確是或者你字邊界多麼複雜的,但一般這樣的事情會爲你工作:

$excerpt = explode(' ', $profile['description']); 
$excerpt = array_slice($excerpt, 0, 100); 
$out .= implode(' ', $excerpt).' '.__('', 'lovestory'); 
1

你可以簡單地使用PHP的換行FUNC如下所示。

$text = "The quick brown fox jumped over the lazy dog."; 
$newText = wordwrap(substr($text, 0, 20), 19, '...'); 
echo $newText; 

將打印當然The quick brown fox...

+0

這是錯誤的!鍵盤:http://codepad.org/hTjLdeDf –

+0

我如何得到這些點在包含超過100個字符的描述的末尾? – user2382274

+0

@ user2382274查看更新的答案 –