0

元の文字列を再生成できるpreg_splitように、 で配列を生成する必要があります。implode('', $array)`preg_split の

$str = 'this is a test "some quotations is her" and more';
$array = preg_split('/( |".*?")/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

の配列を生成します

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

元の文字列の正確なパターンで配列を生成するには、引用符の前後のスペースにも注意する必要があります。

たとえば、文字列が の場合test "some quotations is here"and、配列は次のようになります。

Array
(
        [0] => test
        [1] => 
        [2] => "some quotations is here" 
        [3] => and
)

注: 編集は @micel との最初の議論に基づいて行われました。

4

2 に答える 2

2

これはあなたのために働きますか?

preg_split('/( ?".*?" ?| )/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
于 2012-12-22T08:40:01.397 に答える
1

これでうまくいくはずです

$str = 'this is a test "some quotations is her" and more';
$result = preg_split('/(?:("[^"]+")|\b)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$result = array_slice($result, 1,-1);

出力

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] =>  
    [8] => "some quotations is her"
    [9] =>  
    [10] => and
    [11] =>  
    [12] => more
)

再建

implode('', $result);
// => this is a test "some quotations is her" and more
于 2012-12-22T09:08:27.200 に答える