(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;
}
我尝试在没有拆分单词的情况下进行拆分
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;
}
这样的东西会在最后一个完整单词上分裂,而不会打断单词。
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;
}
感谢您的帮助。我根据你的建议更正了我的代码。最终版本是:
function summary($posttext){
$limit = 60;
if (strlen($posttext)<$limit){
$posttext .= "..";
}else {
$spacepos = strpos($posttext," ",$limit);
$posttext = substr($posttext,0,$spacepos)."..";
}
return $posttext;
}