php
  • preg-split
  • 2011-04-22 85 views 1 likes 
    1

    我使用preg_split()從字符串得到句子的陣列。使preg_split()問題包含字符串「和」

    $sentences = preg_split("/([.?!\r\n]+)/", $text, 0, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); 
    

    但當$text包含 '&',例如:

    $text = 'this is test. we are testing this & we are over.'; 
    

    那麼它停止 '&' 後匹配。

    +0

    你能否澄清 「這個我們停止後&」?它停止解析字符串還是它在&符號(&)處分裂或者什麼? – Compeek 2011-04-22 21:07:43

    +0

    我會更新你的正則表達式來捕捉更多的句子類型,而不是下降了'.'。 '([^。?!] +(= [ '「] \ s *)(?:?!] ['?」[。?!]] \ s *))'爲我工作,但我可能錯過了其他模糊的類型的句子結尾/開始。得到比賽後(不分裂),運行修剪擺脫空間。 – 2011-04-22 21:33:09

    回答

    1

    你使preg_split正確處理句子&符號,例如:

    $text = 'Sample sentence. Another sentence! Sentence with the special character & (ampersand). Last sentence.'; 
    $sentences = preg_split("/([.?!\r\n]+)/", $text, 0, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); 
    print_r($sentences); 
    

    輸出:

    Array 
    (
        [0] => Sample sentence 
        [1] => . 
        [2] => Another sentence 
        [3] => ! 
        [4] => Sentence with the special character & (ampersand) 
        [5] => . 
        [6] => Last sentence 
        [7] => . 
    ) 
    
    +0

    讓我再次檢查 – Yalamber 2011-04-22 21:13:35

    +0

    這是錯誤使用Ajax,我用文字與發送和splited it.php工作正常。這是ajax的問題​​。 – Yalamber 2011-04-22 21:27:24

    +0

    我很高興您的問題已經解決了:) – Anne 2011-04-22 21:31:21

    0

    腳本:

    $text = 'this is test. we are testing this & we are over.'; 
    $sentences = preg_split("/([.?!\r\n]+)/", $text, 0, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); 
    echo '<pre>'.print_r($sentences, true).'</pre>'; 
    

    我的輸出:

    Array 
    (
        [0] => this is test 
        [1] => . 
        [2] => we are testing this & we are over 
        [3] => . 
    ) 
    

    我不明白你的問題。

    相關問題