2017-01-27 103 views
2

我想在字符串中的數組拆分和值存儲在表中,以陣列的字符串分割 的字符串是如何根據需要ccondition

$string="34=No,46=fgbfb,48=NA,29=NA,45=dsd,49=InConclusive,43=1BHK,35=NA,38=12,39=2,27=q1,41=Others,52=fgfdg,47=fgfg,31=Chawl,33=UpperMiddleClass,37=SelfOwned,30=fdgfdgb,50=fgfdgb,51=fgfdg,32=NA,44=[Refrigerator,Airconditioner]"; 

我試過爆炸(「」,$串); 但我不想要分割對象陣列,即(44 = [冰箱,空調器])此我要像44和冰箱,空調器

預期結果: -

Array ( 
     [0] => 34=No 
     [1] => 46=fgbfb 
     [2] => 48=NA 
     [3] => 29=NA 
     [4] => 45=dsd 
     [5] => 49=InConclusive 
     [6] => 43=1BHK 
     [7] => 35=NA 
     [8] => 38=12 
     [9] => 39=2 
     [10] => 27=q1 
     [11] => 41=Others 
     [12] => 52=fgfdg 
     [13] => 47=fgfg 
     [14] => 31=Chawl 
     [15] => 33=UpperMiddleClass 
     [16] => 37=SelfOwned 
     [17] => 30=fdgfdgb 
     [18] => 50=fgfdgb 
     [19] => 51=fgfdg 
     [20] => 32=NA 
     [21] => 44=[Refrigerator,Airconditioner] 
    ) 
+0

使用另一個分隔符如果您無法控制字符串中的分隔符,可以使用preg_replace('/,(\ d + =)/','XXX $ 1'替換它。使用新分隔符(XXX)代替 –

+0

舉個例子吧 –

+0

不用勺子喂,先試一下 –

回答

2

解其工作在所有可能的情況: -

<?php 
$string="34=No,46=fgbfb,48=NA,29=NA,45=dsd,49=InConclusive,43=1BHK,35=NA,38=12,39=2,27=q1,41=Others,52=fgfdg,47=fgfg,31=Chawl,33=UpperMiddleClass,37=SelfOwned,30=fdgfdgb,50=fgfdgb,51=fgfdg,32=NA,44=[Refrigerator,Airconditioner]"; 

$string = str_replace(["[","]"], ["{","}"], $string); // convert `[` to `{` and `]` to `}` 
$array = preg_split('/(,)(?=(?:[^}]|{[^{]*})*$)/',$string); // split string by `,` and ignore `,` between `{}` 
echo "<pre/>";print_r($array); // print array 
foreach ($array as &$ar){ // iterate through array 
    $ar = str_replace(["{","}"], ["[","]"], $ar); // convert `{` to `[` and `}` to `]` 

} 

echo "<pre/>";print_r($array); // print desired array 

輸出: - https://eval.in/725457

2

只要使用適當的正則表達式與preg_match_all

/\d+=(?:\[[^]]*]|[^,]*)/ 

regex demo

詳細

  • \d+ - 1+位數
  • = - 一個=
  • (?:\[[^]]*]|[^,]*) - 無論是2個備選方案:
    • \[[^]]*] - 一個[隨後與0+除]和t之外的字符母雞]
    • | - 或
    • [^,]* - 0+字符比,其他。

如果陣列可以嵌套[...]裏面,你就需要使用一些更復雜的正則表達式(demo):

/\d+=(?:(\[(?:[^][]++|(?1))*])|[^,]*)/ 

PHP demo

$string="34=No,46=fgbfb,48=NA,29=NA,45=dsd,49=InConclusive,43=1BHK,35=NA,38=12,39=2,27=q1,41=Others,52=fgfdg,47=fgfg,31=Chawl,33=UpperMiddleClass,37=SelfOwned,30=fdgfdgb,50=fgfdgb,51=fgfdg,32=NA,44=[Refrigerator,Airconditioner]"; 
preg_match_all('~\d+=(?:\[[^]]*]|[^,]*)~', $string, $results); 
print_r($results[0]); 
+0

@Anant:感謝您的評論,我沒有注意到格式是破碎:)修正。 –

+0

不客氣。 –