I wanted to be able to take a string of text, a blog entry in this case, and crop it down to the nearest sentence to a given maximum length value. I am sure this function exists in php, but I couldn’t find it so I wrote my own and figured some of you might find this handy:

function nearestSentence($s) {
    //Max length of string before 
    //looking for last sentence.
    $maxL = 350;

    //Strip html tags and convert 
    //html entities (like &) 
    //to single characters before counting.
    $toCount = strip_tags(html_entity_decode($s));

    //Crop the string down to the max length.
    if (strlen($toCount) <= $maxL) {
        $s2 = $s;
    } else {
        $s2 = substr($toCount, 0, $maxL);
    }
    //Look for position of the last ., ?, or !
    $lastPunct = max(strrpos($s2, '.'), strrpos($s2, '?'), strrpos($s2, '!'));
    //Crop the string again down to the nearest punctuation.
    $s3 = substr($s2, 0, $lastPunct+1);
    //Return string with html entites re-inserted.
    return htmlentities($s3);
}

So, if you had some text like:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat? Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis! At vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla?

Then, you would get:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat?

If you have some flexibility for the length of your blurb, I think this looks a lot better than just cropping your string down to a particular length and adding… but maybe that’s just me.