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
)

注意:编辑是根据与@mikel 的初步讨论进行的。

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 回答