Returning first sentence from variable in PHP

2020-07-22 17:00发布

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?

标签: php regex
3条回答
手持菜刀,她持情操
2楼-- · 2020-07-22 17:37

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

function firstSentence($string) {
      $sentences = explode(".", $string);
      return $sentences[0];
}
查看更多
冷血范
3楼-- · 2020-07-22 17:39

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;

}
查看更多
爷、活的狠高调
4楼-- · 2020-07-22 17:47
/**
 * 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);
查看更多
登录 后发表回答