2011-07-02 58 views
3

我也發現了類似的線程已經在那裏我得到:返回第一句從變量在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; 


}?> 

這似乎當一個句子作爲段落的結尾結束時,不考慮第一句話。有任何想法嗎?

+0

可以包含一個鏈接到你拿到代碼,請原來的線程?沒關係,我想我知道了,[有沒有人有一個PHP代碼段來抓取字符串中的第一個「句子」?](http://stackoverflow.com/questions/1135467/does-anyone-have-a -的碼換抓住最第一句子中-A-STR -php-片段)。 – 2011-07-02 00:49:08

+0

你有沒有看過其他任何「正則表達式」問題的第一句話,像這樣,[First Sentence Regex](http://stackoverflow.com/questions/1569091/first-sentence-regex)? – 2011-07-02 00:51:03

+0

這一個看起來很有前途/^.{150,}?[??]]+(?=\s|$)/但不知道如何將它合併到一個函數中 – Trinitrotoluene

回答

1

下面是正確的語法,對不起,我的第一個反應:

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

如果你的句子有不同的結尾字符?防爆。 「?」,「!」 etc ...... – brooklynsweb

+1

$ string =「索羅古先生的解決方案不太好......」; –

+0

這絕對不是可接受的解決方案。 Sverri Olsen說得對。 – Bangkokian

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); 
0

情況下你需要的句子數爲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; 

}