Trinitrotoluene
Trinitrotoluene

Reputation: 1458

Returning first sentence from variable in PHP

I have found a similar thread already where I got:

$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);

This doesn't seem to work in my function though:

<?function first_sentence($content) {
    $content = html_entity_decode(strip_tags($content));   
    $content = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $content);
    return $content;


}?>

It seems to be not taking into account the first sentence when a sentence ends as the end of a paragraph. Any ideas?

Upvotes: 3

Views: 3737

Answers (3)

user3200582
user3200582

Reputation: 43

In case you need n number of sentences, you can use the following code. I adapted code from: https://stackoverflow.com/a/22337095 & https://stackoverflow.com/a/10494335

/**
 * Get n number of first sentences of a string.
 *
 * If no ending punctuation is found then $text will
 * be returned as the sentence. If $strict is set
 * to TRUE then FALSE will be returned instead.
 *
 * @param  string  $text   Text
 * int     $no_sentences   Number of sentences to extract
 * @param  boolean $strict Sentences *must* end with one of the $end characters
 * @param  string  $end    Ending punctuation
 * @return string|bool     Sentences or FALSE if none was found
 */

function firstSentences($text, $no_sentences, $strict = false , $end = '.?!;:') {

    $result = preg_split('/(?<=['.$end.'])\s+/', $text, -1, PREG_SPLIT_NO_EMPTY);

    if (empty($result)) {
        return ($strict ? false : $text);
    }

    $ouput = '';
    for ($i = 0; $i < $no_sentences; $i++) {
        $ouput .= $result[$i].' ';
    }
    return $ouput;

}

Upvotes: 1

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13273

/**
 * Get the first sentence of a string.
 *
 * If no ending punctuation is found then $text will
 * be returned as the sentence. If $strict is set
 * to TRUE then FALSE will be returned instead.
 *
 * @param  string  $text   Text
 * @param  boolean $strict Sentences *must* end with one of the $end characters
 * @param  string  $end    Ending punctuation
 * @return string|bool     Sentence or FALSE if none was found
 */
function firstSentence($text, $strict = false, $end = '.?!') {
    preg_match("/^[^{$end}]+[{$end}]/", $text, $result);
    if (empty($result)) {
        return ($strict ? false : $text);
    }
    return $result[0];
}

// Returns "This is a sentence."
$one = firstSentence('This is a sentence. And another sentence.');

// Returns "This is a sentence"
$two = firstSentence('This is a sentence');

// Returns FALSE
$three = firstSentence('This is a sentence', true);

Upvotes: 6

Thomas Thorogood
Thomas Thorogood

Reputation: 2357

Here's correct syntax, sorry for my first response:

function firstSentence($string) {
      $sentences = explode(".", $string);
      return $sentences[0];
}

Upvotes: 0

Related Questions