Using PHP to print only the first sentence

Ever wanted to pull just the first sentence of a text and print it? If yes, this is for you.

Simply add the following code (in PHP) to your page/system before the actual HTML stuff begins:

< ?php
function getFirstSentence($string)
{
    // First remove unwanted spaces - not needed really
    $string = str_replace(" .",".",$string);
    $string = str_replace(" ?","?",$string);
    $string = str_replace(" !","!",$string);
    // Find periods, exclamation- or questionmarks with a word before but not after.
    // Perfect if you only need/want to return the first sentence of a paragraph.
    preg_match('/^.*[^\s](\.|\?|\!)/U', $string, $match);
    return $match[0];
} 
?>

Then call the function somewhere on the page where you want the text to appear:

< ?php
    // The $string below could/should be a text string pulled from your database or similar
    $string = "Lentence oneasdasd asd asd asdasd, ?. Sentence two? Sentence three! Sentence four.";
    echo getFirstSentence($string);
?>

Comes in handy for search result pages, page titles and similar listings.

About Author