Search code examples
phpfunctionsummary

PHP - a more compact function for this process?


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

Solution

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