如何在preg_split(PHP)中停止在一对第二分隔符内拆分?

时间:2012-12-22 08:35:14

标签: php regex preg-split

我需要使用preg_split生成数组,因为implode('', $array)可以重新生成原始字符串。

$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的初步讨论做出的。

2 个答案:

答案 0 :(得分:2)

这对你有用吗?

preg_split('/( ?".*?" ?| )/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

答案 1 :(得分: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