How to Get The First Sentence from a String in PHP

PHP snippet to return the first sentence from a string. Very useful for generating post or page excerpts, extracts or meta descriptions.

By Tim Trott | PHP Tutorials | January 24, 2009

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.

php
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.

php
$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.
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 1 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. JD

    On Friday 4th of November 2011, John Deere said

    A better way would be to use regex

    php
    function getFirstSentence($string) {
      $sentence = preg_split( &#039;/(\.|!|\?)\s/&#039;, $string, 2, PREG_SPLIT_DELIM_CAPTURE );
      return $sentence[&#039;0&#039;] . $sentence[&#039;1&#039;];
    }