My variable $content
contains my text. I want to create an excerpt from $content
and display the first sentence and if the sentence is shorter than 15
Here's a quick helper method that I wrote to get the first N
sentences of a given body of text. It takes periods, question marks, and exclamation points into account and defaults to 2 sentences.
function tease($body, $sentencesToDisplay = 2) {
$nakedBody = preg_replace('/\s+/',' ',strip_tags($body));
$sentences = preg_split('/(\.|\?|\!)(\s)/',$nakedBody);
if (count($sentences) <= $sentencesToDisplay)
return $nakedBody;
$stopAt = 0;
foreach ($sentences as $i => $sentence) {
$stopAt += strlen($sentence);
if ($i >= $sentencesToDisplay - 1)
break;
}
$stopAt += ($sentencesToDisplay * 2);
return trim(substr($nakedBody, 0, $stopAt));
}