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

时间:2021-09-27 03:17:32

I need to generate an array with preg_split, as implode('', $array) can re-generate the original string. `preg_split of

我需要使用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);

generates an array of

生成一个数组

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
)

I need to take care of the space before/after the quotation marks too, to generate an array with the exact pattern of the original string.

我需要在引号之前/之后处理空间,以生成具有原始字符串的确切模式的数组。

For example, if the string is test "some quotations is here"and, the array should be

例如,如果字符串是测试“某些引用在这里”,那么数组应该是

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

Note: The edit has been made based on initial discussion with @mikel.

注意:编辑是基于与@mikel的初步讨论而完成的。

2 个解决方案

#1


2  

Will this work for you ?

这对你有用吗?

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

#2


1  

This should do the trick

这应该可以解决问题

$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);

Output

产量

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

Reconstruction

重建

implode('', $result);
// => this is a test "some quotations is her" and more

#1


2  

Will this work for you ?

这对你有用吗?

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

#2


1  

This should do the trick

这应该可以解决问题

$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);

Output

产量

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

Reconstruction

重建

implode('', $result);
// => this is a test "some quotations is her" and more