我已经在那里找到了一个类似的线程:
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);
Run Code Online (Sandbox Code Playgroud)
不过,这在我的函数中似乎不起作用:
<?function first_sentence($content) {
$content = html_entity_decode(strip_tags($content));
$content = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $content);
return $content;
}?>
Run Code Online (Sandbox Code Playgroud)
当一个句子作为一个段落结束时,它似乎没有考虑到第一句。有任何想法吗?
/**
* 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);
Run Code Online (Sandbox Code Playgroud)