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:
<?php
preg_match('/^([^.!?\s]*[\.!?\s]+){0,n}/', strip_tags($text), $abstract);
echo $abstract[0];
?>
… or truncate after n sentences:
<?php
preg_match('/^([^.!?]*[\.!?]+){0,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:
<?php
function abstract( $string, $len ) {
if ( strlen($string) > $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 abstract( $string, 180 );
?>
I am a British web designer and developer, working for the United Nations out in Geneva, Switzerland, where I live with my lovely wife Zoe.