【问题标题】:How to stop splitting within a pair of second delimiter in preg_split (PHP)?如何在 preg_split (PHP) 中的一对第二分隔符内停止拆分?
【发布时间】:2012-12-22 08:35:14
【问题描述】:

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

$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 的初步讨论进行的。

【问题讨论】:

    标签: php regex preg-split


    【解决方案1】:

    这对你有用吗?

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

    【讨论】:

    • 抱歉,我对这个解决方案有一个小问题。它将在引号前后添加双空格(第一个分隔符)。事实上,它会同时对两个分隔符起作用。
    • 感谢您的编辑,但现在它将删除所有空格。当然,它在我的问题中也很糟糕。无论如何,我需要有一个字符串的精确模式数组。如果引号前后有空格或没有空格;我需要将它们放在生成的数组中。
    【解决方案2】:

    这应该可以解决问题

    $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
    

    【讨论】:

    • 谢谢,在我编辑时,我需要在数组中有空格(第一个分隔符)。它可以在引号之前/之后出现或不存在。
    • 感谢编辑,但implode('', $array)如果引号后没有空格,将不会生成原始字符串;例如her"and。这适用于引号前的空格/无空格,但不适用于引号之后。
    • 所有,它确实重建了原始字符串。你甚至可以看到her"之后的数组中的空格(空值)。
    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多