2012-05-08 90 views
10

我一直在使用爆炸段落成句子在PHP

explode(".",$mystring) 

拆分成段的句子。但是這不包括以不同的標點符號結尾的句子,例如! ? :;

有沒有使用數組作爲分隔符而不是單個字符的方法?另外還有另一種使用各種標點符號的簡單方法嗎?

我試圖

explode(("." || "?" || "!"),$mystring) 

希望,但它沒有工作...

+0

使用正則表達式匹配圖案和所述值存儲在變量中,通過該變量作爲參數爆炸 – sree

+0

看看http://stackoverflow.com/questions/5032210/php-sentence-boundaries-detection – Boby

回答

6

你可以這樣做:

preg_split('/\.|\?|!/',$mystring); 

或(更簡單):

preg_split('/[.?!]/',$mystring); 
+1

此方法從最終字符串中刪除完整的停止等。 – 472084

0
$mylist = preg_split("/[\.|\?!:;]/", $mystring); 
0

您不能有多個分隔符用於爆炸。這就是preg_split();的用途。但即使如此,它在分隔符處爆炸,所以你會得到沒有標點符號的句子。 您可以使preg_split一步越走越標誌它返回他們在PREG_SPLIT_DELIM_CAPTURE自己的元素,然後運行一些循環內爆句和下punctation標記返回數組中,或者只是使用preg_match_all();

preg_match_all('~.*?[?.!]~s', $string, $sentences); 
1
preg_split('/\s+|[.?!]/',$string); 

一個可能的問題可能是如果有一個電子郵件地址,因爲它可以將它分成一半的新線。

2

假設你真正想要對最終結果的標點符號標記,你有沒有嘗試過:

$mystring = str_replace("?","?---",str_replace(".",".---",str_replace("!","!---",$mystring))); 
$tmp = explode("---",$mystring); 

這會使你的標點符號機智。

0

您可以嘗試preg_split

$sentences = preg_split("/[\.\?\!,;]+/", $mystring); 

請注意,這將刪除標點符號。如果你想去掉開頭或結尾的空白以及

$sentences = preg_split("/[\.\?\!,;]+\s+?/", $mystring); 
11

可以使用preg_split()PCRE lookahead condition組合的每次出現後的字符串分割.;:?!,..同時保持實際標點符號完好:

代碼:

$subject = 'abc sdfs. def ghi; this is [email protected]! asdasdasd? abc xyz'; 
// split on whitespace between sentences preceded by a punctuation mark 
$result = preg_split('/(?<=[.?!;:])\s+/', $subject, -1, PREG_SPLIT_NO_EMPTY); 
print_r($result); 

結果:

Array 
(
    [0] => abc sdfs. 
    [1] => def ghi; 
    [2] => this is [email protected]! 
    [3] => asdasdasd? 
    [4] => abc xyz 
)