如何根据所需的条件将字符串拆分为数组

how to split the string in to array based on required ccondition

我想将字符串拆分成数组并将值存储在 table 字符串是

$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]";

我试过 explode(',',$string); 但我不想拆分对象数组 ie(44=[Refrigerator,Airconditioner]) 我想要 44 和 Refrigerator,Airconditioner

预期结果:-

 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] 
    )

适用于所有可能情况的解决方案:-

<?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

只需使用正确的正则表达式 preg_match_all:

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

参见regex demo

详情:

  • \d+ - 1+ 位数
  • = - 一个 =
  • (?:\[[^]]*]|[^,]*) - 两种选择之一:
    • \[[^]]*] - [ 后跟 ] 以外的 0+ 个字符,然后是 ]
    • | - 或
    • [^,]* - ,.
    • 以外的 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]);