从PHP中的变量返回第一句话

时间:2011-07-02 00:33:17

标签: php regex

我已经找到了一个类似的线程:

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

这似乎不适用于我的功能:

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


}?>

当句子以段落结尾结束时,似乎没有考虑第一句话。有什么想法吗?

3 个答案:

答案 0 :(得分:4)

/**
 * 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);

答案 1 :(得分:1)

这是正确的语法,对不起我的第一个回复:

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

答案 2 :(得分:0)

如果您需要n个句子,可以使用以下代码。 我修改了以下代码:https://stackoverflow.com/a/22337095&amp; 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;

}