【问题标题】:how to split the string in to array based on required ccondition如何根据所需的ccondition将字符串拆分为数组
【发布时间】:2017-01-27 05:19:28
【问题描述】:

我想将字符串拆分为数组并将值存储在表中 字符串是

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

【问题讨论】:

  • 使用另一个分隔符。如果您无法控制字符串中的分隔符,您可以使用 preg_replace('/,(\d+=)/', 'XXX$1' 替换它。使用您的新分隔符 (XXX) 来替换它
  • 你能给我举个例子吗?
  • 没有勺子喂食。先试试吧
  • 预期结果是什么?
  • 请使用两个分隔符。一个适合 44 岁,其他的会有所不同

标签: php string split explode


【解决方案1】:

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

<?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 位以上
    • = - 一个=
    • (?:\[[^]]*]|[^,]*) - 两种选择之一:
      • \[[^]]*] - [ 后跟 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]);
    

    【讨论】:

    • @Anant:感谢您的评论,我没有注意到格式被破坏了 :) 已修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多