5

如何合并两个分隔符preg_split?例如:

$str = "this is a test , and more";
$array = preg_split('/( |,)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($array);

将产生一个数组

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] =>  
    [8] => 
    [9] => ,
    [10] => 
    [11] =>  
    [12] => and
    [13] =>  
    [14] => more
)

但我想得到

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] => ,
    [8] => and
    [9] =>  
    [10] => more
)

实际上,我想在两个分隔符是邻居时合并数组元素。换句话说,如果下一部分是第二个分隔符,则忽略第一个分隔符。

4

3 回答 3

3

尝试使用字符类:/[ ,]+/

+是一个量词,意思是“1或更多”

于 2012-12-19T00:45:46.467 回答
2

如何确保首先不会发生这种情况:

<?php
    $str = "this is a test , and more";
    $str=preg_replace('/ *, */',',',$str);
    $array = preg_split('/( |,)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
    print_r($array);
?>

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] => ,
    [8] => and
    [9] =>  
    [10] => more
)
于 2012-12-19T00:53:52.673 回答
1

使用/([, ]+)/它有效。见键盘

于 2012-12-19T00:56:57.857 回答