2014-04-21 115 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查看更新的答案 –