5

で2つの区切り文字をマージする方法は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
)

実際、2つの区切り文字が隣接している場合は、配列要素をマージしたいと思います。つまり、次の部分が2番目の区切り文字である場合、最初の区切り文字を無視します。

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 に答える