String abstract PHP function

As a web developer, I’m often trying to squeeze text into small spaces, and sometimes the only way is to create a summary, or abstract of the text.

A lot of abstract functions will truncate after n words:

n}/', strip_tags($text), $abstract);
echo $abstract[0];
?>

… or truncate after n sentences:

n}/', strip_tags($text), $abstract);
echo $abstract[0];
?>

… but this isn’t always enough. Three sentences, (or 50 words for that matter), could run anywhere between 150 and 450 characters long, which is a big variation if you only have room to display 180 characters! So here’s my reusable abstract function that will…

… truncate after the last word that appears within your specified character limit:

 $len ) {
    $pos = ( $len - stripos(strrev(substr($string, 0, $len)), ' ') );
    $sum = substr($string, 0, $pos-1);
    $chr = $sum[strlen($sum)-1];
    if ( strpos($chr, '.,!?;:') ) {
       // STRIP LAST CHAR
       $sum = substr($sum, 0, strlen($sum)-1);
    }
    // ADD ELLIPSIS
    return $sum."…";
  } else {
    return $string;
  }
}

echo excerpt( $string, 180 );
?>

Leave a Reply

Your email address will not be published. Required fields are marked *