Возвращение первого предложения из переменной в PHP

Я нашел подобную нить уже там, где я получил:

$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; }?> 

Кажется, что он не учитывает первое предложение, когда предложение заканчивается как конец абзаца. Есть идеи?

Related of "Возвращение первого предложения из переменной в PHP"

Вот правильный синтаксис, извините за мой первый ответ:

 function firstSentence($string) { $sentences = explode(".", $string); return $sentences[0]; } 
 /** * 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); 

Если вам нужно n количество предложений, вы можете использовать следующий код. Я адаптировал код из: 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; }