两次爆炸字符串

时间:2016-11-23 11:16:25

标签: php explode

我有一个像这样的字符串:

87||1|nuovo#88||4|#209|||#89|||#41||1|#5|||#3||1|116#20|||#13||3|#148|||

模式是:
Id1|Mq1|Q.ta1|Tipo1#Id2|Mq2|Q.ta2|Tipo2#Id3|Mq3|Q.ta3|Tipo3 等等......

基本上每个项目有4个以“|”分隔的属性每个项目用“#”分隔

我需要将字符串分解为每个项目的属性都有单个变量。

至于现在我在这里:

<?php
$str = "87||1|nuovo#88||4|#209|||#89|||#41||1|#5|||#3||1|116#20|||#13||3|#148|||#36|||91#29|||68";
$caratteristica = print_r (explode("#",$str));
?>

这给了我这个结果:

Array ( [0] => 87||1|nuovo [1] => 88||4| [2] => 209||| [3] => 89||| [4] => 41||1| [5] => 5||| [6] => 3||1|116 [7] => 20||| [8] => 13||3| [9] => 148||| [10] => 36|||91 [11] => 29|||68 ) 

这个数组的每个元素都需要四个变量
(类似于$id[], $mq[],$qt[],$tipo[])。

3 个答案:

答案 0 :(得分:1)

<?php
$input = '87||1|nuovo#88||4|#209|||#89|||#41||1|#5|||#3||1|116#20|||#13||3|#148|||';
$items = explode('#', $input);
$result = [];
# or $id = $mq = $qr = $tipo = [];
foreach ($items as $i) {
  list($id, $mq, $qr, $tipo) = explode('|', $i);
  $result[] = ['id' => $id, 'mq' => $mq, 'qr' => $qr, 'tipo' => $tipo];
  # or $id[] = $id; $mq[] = $mq; $qr[] = $qr; $tipo[] = $tipo;
}

答案 1 :(得分:0)

改变Jiri的代码。

替换此行

list($id, $mq, $qr, $tipo) = explode('|', $i);

list($id[], $mq[], $qr[], $tipo[]) = explode('|', $i);

答案 2 :(得分:0)

尝试以下代码

    $str = "87||1|nuovo#88||4|#209|||#89|||#41||1|#5|||#3||1|116#20|||#13||3|#148|||#36|||91#29|||68";
$caratteristica = explode("#",$str);

foreach ($caratteristica as $value) {
 list($id[], $mq[], $qr[], $tipo[]) = explode('|', $value);
}

// For check the result
echo "<pre/>";
print_r($id);

print_r($mq);

print_r($qr);

print_r($tipo);

我得到了以下答案

    Array
(
    [0] => 87
    [1] => 88
    [2] => 209
    [3] => 89
    [4] => 41
    [5] => 5
    [6] => 3
    [7] => 20
    [8] => 13
    [9] => 148
    [10] => 36
    [11] => 29
)
Array
(
    [0] => 
    [1] => 
    [2] => 
    [3] => 
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
    [10] => 
    [11] => 
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 
    [3] => 
    [4] => 1
    [5] => 
    [6] => 1
    [7] => 
    [8] => 3
    [9] => 
    [10] => 
    [11] => 
)
Array
(
    [0] => nuovo
    [1] => 
    [2] => 
    [3] => 
    [4] => 
    [5] => 
    [6] => 116
    [7] => 
    [8] => 
    [9] => 
    [10] => 91
    [11] => 68
)