包含'&'的字符串的preg_split()问题

时间:2011-04-22 20:59:36

标签: php 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.';

然后它会在'&'之后停止匹配。

2 个答案:

答案 0 :(得分: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] => .
)

答案 1 :(得分: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] => .
)

我不明白你的问题。