php
  • preg-split
  • 2011-04-22 60 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] => . 
    ) 
    

    我不明白你的问题。

    相关问题