سؤال

(PHP) Could be this function made more compact? I use this function for writing summary of posts on homepage. It finds first space after the limit length of text because to avoid the divsion of words for ex. My notebook is fine -> summary: My notebook.. its not should be My note...

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;
}
هل كانت مفيدة؟

المحلول

My try to breaking without split words

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

نصائح أخرى

Something like this will split on the last full word without breaking the word.

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

Thanks for your helps.I corrected my codes according to your suggestions.And the final version is this:

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

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

$posttext .= "..";  

}else {
$spacepos = strpos($posttext," ",$limit);   
$posttext = substr($posttext,0,$spacepos)."..";
}
return $posttext;   
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top