2012-12-22 36 views
0

我需要用preg_split生成一個數組,因爲implode('', $array)可以重新生成原始字符串。 `的如何在preg_split(PHP)中的一對第二分隔符內停止分割?

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

使preg_split生成的

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

這是否適合您?

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

完美的作品!我在正則表達式上有一點創意:) – Googlebot

+0

對不起,我有這個解決方案的一個小問題。它將在引號前後添加雙倍空間(第一個分隔符)。事實上,它將同時與兩個分隔符合作。 – Googlebot

+0

噢,我編輯了一個新版本,你可以試試嗎? – mikel

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 
+0

謝謝,當我編輯時,我需要在數組中有空格(第一個分隔符)。它可能在引號前/後出現或缺失。 – Googlebot

+0

@所有,我更新了我的答案。請看看:) –

+0

感謝您的編輯,但是'implode('',$ array)'如果引號後面沒有空格,將不會生成原始字符串;例如'her「和'''',這將在引號之前的空格/空格之間起作用,但不會在之後。 – Googlebot

相關問題