Search code examples
phparraysmultidimensional-arraytext-parsing

Parse a multiline string with two delimiters per line into an array of associative rows


I found a few posts to explode data as array, but mine is bit specific because the data has 2 parts

I have this

title=Title1|link=Link1
title=Title2|link=Link2

and result I need is this

Array
(
    [0] => Array
        (
            [title] => Title1
            [link] => Link1
        )

    [1] => Array
        (
            [title] => Title2
            [link] => Link2
            
        )

)

data is coming from texarea separated by \n so the data you see is actual data.


Solution

  • I'm more a fan of explode() than preg_match() when you don't actually need regular expressions.

    <?php
    
    $text="title=Title1|link=Link1\ntitle=Title2|link=Link2";
    
    $result=array();
    $count=0;
    
    // line by line...
    foreach (explode("\n", $text) as $line) {
      // variable by variable...
      foreach (explode("|", $line) as $vars) {
        // separate LHS from RHS.
        $parts=explode("=", $vars);
        $result[$count][$parts[0]]=$parts[1];
      }
      $count++;
    }
    
    print_r($result);
    
    ?>
    

    Don't forget to add code to handle lines that don't match the pattern you expect. Input validation is important.