2013-03-07 36 views
0

用下面的字符串:PHP使preg_split定界符模式,分裂人品鏈

$str = '["one","two"],a,["three","four"],a,,a,["five","six"]'; 

preg_split(delimiter pattern, $str); 

我會如何來建立定界符模式獲得這樣的結果:

$arr[0] = '["one","two"]'; 
$arr[1] = '["three","four"]'; 
$arr[2] = '["five","six"]'; 

在其他字,有沒有辦法在模式'拆分',a,'AND',a,a,'但是檢查',a ,, a,'首先是因爲',a,'是子字符串',一,,一,'?

在此先感謝!

+3

你沒事使用的preg_match呢? – Pitchinnate 2013-03-07 22:00:46

+0

可能重複的[如何分割字符串','除非','在括號內使用正則表達式?](http://stackoverflow.com/questions/732029/how-to-split-string-by-unless-is -within-brackets-using-regex)或[PHP:在逗號分隔字符串,但不在大括號或引號之間?](http://stackoverflow.com/q/15233953) – mario 2013-03-07 22:03:38

+0

是的,我會很好地使用preq_match 。 – 2013-03-07 22:09:50

回答

1

如果它只能是,a,,a,,a,,那麼這應該足夠:

preg_split("/(,a,)+/", $str); 
+0

非常感謝!簡單而有效! – 2013-03-07 22:20:22

0

看看這個代碼:

$result = array(); 

preg_match_all("/(\[[^\]]*\])/", '["one","two"],a,["three","four"],a,,a,["five","six"]', $result); 

echo '<pre>' . print_r($result, true); 

它會返回:

Array 
(
    [0] => Array 
     (
      [0] => ["one","two"] 
      [1] => ["three","four"] 
      [2] => ["five","six"] 
     ) 

    [1] => Array 
     (
      [0] => ["one","two"] 
      [1] => ["three","four"] 
      [2] => ["five","six"] 
     ) 
) 
1

它看起來像你實際試圖做的是分開方括號內的部分。你能做到這一點,像這樣:

$arr = preg_split("/(?<=\])[^[]*(?=\[)/",$str); 
+0

我測試了你的模式,應該改成:'/(?<= \')[^ [] *(?= \ [)/' – 2013-03-07 22:09:30

+0

是的,謝謝! – 2013-03-07 22:20:46