How to Get The First Sentence from a String in PHPPHP snippet to return the first sentence from a string. Very useful for generating post or page excerpts, extracts or meta descriptions.
This PHP function will get the first sentence from a string delimited by a full stop. If a string contains and exclamation, this will also act and an end of sentence.
function getFirstSentence($string) {
$excl = strpos($string,"!");
$stop = strpos($string,".");
if ($excl === false) $excl = 9999;
if ($stop === false) $stop = 9999;
if ($excl < $stop) return $excl + 1;
if ($excl > $stop) return $stop + 1;
}
Example to get first sentence from a string.
$string = "This is a test sentence, which will test the getFirstSentence() function. This is another sentence.";
$firstSentence = getFirstSentence($string);
echo $firstSentence;
The function outputs -
This is a test sentence, which will test the getFirstSentence() function.