我試圖從數據庫文本條目中檢索第一句和最後一句。高級的第一句和最後一句功能
我在這個例子中,做工精細代碼:
$text = "He was doing ok so far, but this one had stumped him. He was a bit lost..."
功能:
function first_sentence($content) {
$pos = strpos($content, '.');
if($pos === false) {
return $content;
}
else {
return substr($content, 0, $pos+1);
}
} // end function
// Get the last sentence
function last_sentence($content) {
$content = array_pop(array_filter(explode('.', $content), 'trim'));
return $content;
} // end function
最後一句功能考慮任何尾隨...的在的結束句子,但都不能應對以下內容:
$text = "Dr. Know-all was a coding master, he knew everything and was reputed the world over. But the Dr. was in trouble..."
結果: Fi第一句:Dr. 最後一句:遇到麻煩
我需要修改函數來考慮'Dr.'和其他這樣的縮寫,如果這是可能的,所以最後的文本變量會出現爲:
第一句:Dr. Know-all是一個編碼大師,他知道一切,並被全世界譽爲 最後一句:但是博士遇到麻煩
可以這樣做嗎?任何幫助非常感謝!
當一個句子以'...'結尾時,你會怎麼做? –
好點! ...或者確實是'!'。我還沒有那麼遠:) 現在它會返回「第一句話是個問題嗎?是的。」我現在可以接受這一點,因爲我認爲越多越好,但是我可能不得不稍後再說,除非有人想把它放在這裏!感謝那。 –
基本上,如果你想接受任意的英文文本,恐怕你將不得不處理一長串特殊情況。對於程序員來說,我會像[語言學家](http://linguistics.stackexchange.com/)一樣成爲一個問題。 –