2013-10-21 63 views
2

我試圖從數據庫文本條目中檢索第一句和最後一句。高級的第一句和最後一句功能

我在這個例子中,做工精細代碼:

$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是一個編碼大師,他知道一切,並被全世界譽爲 最後一句:但是博士遇到麻煩

可以這樣做嗎?任何幫助非常感謝!

+1

當一個句子以'...'結尾時,你會怎麼做? –

+0

好點! ...或者確實是'!'。我還沒有那麼遠:) 現在它會返回「第一句話是個問題嗎?是的。」我現在可以接受這一點,因爲我認爲越多越好,但是我可能不得不稍後再說,除非有人想把它放在這裏!感謝那。 –

+0

基本上,如果你想接受任意的英文文本,恐怕你將不得不處理一長串特殊情況。對於程序員來說,我會像[語言學家](http://linguistics.stackexchange.com/)一樣成爲一個問題。 –

回答

0

您可以檢查您的substr長度,並且只在長度超過3個字符(包括點數)時纔會返回。如果它不大或相等,你可以使用白名單,以免偶然發現諸如「不」,「我」,「我們」,「哦」等詞......拼字遊戲字典應該能夠幫助你:)

1

也許你想過這樣..

,你可以做一個函數來編碼/解碼您搜索的句子前$content;

function encode_content($content){ 
    return $encoded_content = str_replace("Dr.", "Dr#;#", $content); 
} 

你獲取的句子後,再進行解碼:

function decode_content($content){ 
    return $encoded_content = str_replace("Dr#;#", "Dr." , $content); 
} 
+0

謝謝!我已經選擇了這個,它工作得很好:D –

+0

@MrC,我知道它沒有優化..但有一些變化,你可以添加例外,如'...',''','先生。 '...只需在返回字符串之前添加'$ encoded_content = str_replace(「Mr。」,「Mr#;#」,$ encoded_content);''的每個異常行!希望能幫助到你! – Lan

2

您可以通過replacing排除某些字它們。

<? 

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..."; 

$tmp = str_replace("Dr.","Dr____",$text); 
echo $tmm ."\n"; 
echo str_replace("Dr____","Dr.",first_sentence($tmp))."\n"; 
echo str_replace("Dr____","Dr.",last_sentence($tmp)); 

?> 

WORKING CODE

0

只是回答我的問題,把一些新的功能一起給出的答案後,至今

function encode_text($content){ 
    $search = array("Dr.", "i.e.", "Mr.", "Mrs.", "Ms."); // put our potential problems in an array 
    $replace = array("Dr#;#", "i#e#", "Mr#;#", "Mrs#;#", "Ms#;#"); // make them good for first and last sentence functions 
    $encoded_content = str_replace($search, $replace, $content); 
    return $encoded_content; 
} // end encode 

然後,我們只是交換了搜索和周圍替換變量,使我們的解碼功能。現在,它們可以用於上面的第一句和最後一句話功能,並且它很有魅力。添加東西到陣列很簡單,想到什麼是適當的添加壽是不那麼:)

乾杯!