Explode a string into a multidimensional array based on 4 different delimiters which signal how levels are separated

371 views Asked by At

I want to explode a string with different kind of characters.

I already know how to explode a string, I also think I know how I can do it in different levels.

How do you use one of the values as name ($var['name']) instead of having numbers ($var[0])?

I only know how to do this manually in the array, but I don't know how to add it with variables.

In summary I want this string:

title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3

to become this array:

[
    [
        'title' => 'hello',
        'desc' => 'message',
    ],
    [
        'title' => 'lorem',
        'desc' => 'ipsum',
        'ids' => ['1', '2', '3'],
    ],
]

Edit: I made some progress, but it's not quite finished.

<?php
$string = "title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3";
$string = explode("|", $string);
foreach($string as $split){
    $split = explode(";", $split);
    foreach($split as $split2){
        $split2 = explode(":", $split2);
        // more code..
    }
}

Now I need $split2[0] to be the name and $split2[1] to be the value, like the example earlier.

5

There are 5 answers

1
Sean Doe On BEST ANSWER
$input = "title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3";
$items = preg_split("/\|/", $input);
$results = array();
$i = 0;
foreach($items as $item){
     $subItems = preg_split("/;/", $item);
     foreach($subItems as $subItem){
        $tmp = preg_split("/:/", $subItem);
        $results[$i][$tmp[0]] = $tmp[1];
     } 
     $i++;

}

It returns:

array(2) {
  [0]=>
  array(2) {
    ["title"]=>
    string(5) "hello"
    ["desc"]=>
    string(7) "message"
  }
  [1]=>
  array(3) {
    ["title"]=>
    string(5) "lorem"
    ["desc"]=>
    string(5) "ipsum"
    ["ids"]=>
    string(5) "1,2,3"
  }
}

And then process your 'ids' index

2
Glavić On

Why not just use json_encode() / json_decode() or serialize() / unserialize() ?

demo

0
Vlad On

You can convert your string into JSON, then decode json to array. For example:

    $text = 'title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3';

    $json = '[' . preg_replace(
        array("#(.*?):(.*?)(;|\||$)#i", "#\"((.?),(.*?))\"#i", "#(.*?)\|((.+)|$)#i", "#;#"),
        array('"$1":"$2"$3','[$1]', '[{$1}],[{$2}]', ','),
        $text
    ) . ']';

    $res = json_decode($json, true);

See: http://codepad.viper-7.com/ImLULZ

But @Glavić rights.

1
Nambi On

i tried without regex by using explode() with exact output but in the your accepted answer gives id as a string

<?php


$str="title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3";

$a=explode("|",$str)[0];
$b=explode("|",$str)[1];
$c=explode(";",$a)[0];
$d=explode(";",$a)[1];
$f=explode(";",$b)[0];
$g=explode(";",$b)[1];
$i=explode(";",$b)[2];
$e[][explode(":",$c)[0]]=explode(":",$c)[1];
$e[explode(":",$d)[0]]=explode(":",$d)[1];
$e[][explode(":",$f)[0]]=explode(":",$f)[1];
$e[1][explode(":",$g)[0]]=explode(":",$g)[1];
$e[1][explode(":",$i)[0]]=explode(",",explode(":",$i)[1]);

var_dump($e);

output:

array (size=3)
  0 => 
    array (size=1)
      'title' => string 'hello' (length=5)
  'desc' => string 'message' (length=7)
  1 => 
    array (size=3)
      'title' => string 'lorem' (length=5)
      'desc' => string 'ipsum' (length=5)
      'ids' => 
        array (size=3)
          0 => string '1' (length=1)
          1 => string '2' (length=1)
          2 => string '3' (length=1)
0
mickmackusa On

There is absolutely no reason to use regex when all delimiting characters are static/literal -- just use explode(). Explode while looping and on the lowest level, if the value contains a comma, explode on commas to populate the deep subarray.

Code: (Demo)

$string = 'title:hello;desc:message|title:lorem;desc:ipsum;ids:1,2,3';

$result = [];
foreach (explode('|', $string) as $setString) {
    $set = [];
    foreach (explode(';', $setString) as $rowString) {
        [$key, $value] = explode(':', $rowString);
        $set[$key] = str_contains($value, ',') ? explode(',', $value) : $value;
    }
    $result[] = $set;
}
var_export($result);

Output:

array (
  0 => 
  array (
    'title' => 'hello',
    'desc' => 'message',
  ),
  1 => 
  array (
    'title' => 'lorem',
    'desc' => 'ipsum',
    'ids' => 
    array (
      0 => '1',
      1 => '2',
      2 => '3',
    ),
  ),
)