Search code examples
php

Parse a string with two delimiters into an associative array AND how to get the last tag in an HTML string


  1. Question

    i have string like this $str="a|apple||b|bat||c|cat||d|dog";

    from the above string i want to create a array dynamically n that newly created array shud look like this Array ( [a] => apple [b] => bat [c] => cat [d] => dog )

  2. Question

    i have html string like this

                $html_string="<div>Content Div1</div>
                              <div>Content Div2</div>
                              <div>Content Div3</div>";
    

how can i get 3rd DIV ,resulting answer should be like this

              $ans="<div>Content Div3</div>" ;

Please anyone help me


Solution

  • for the first one

    $str = "a|apple||b|bat||c|cat||d|dog";
    $new_array = array();
    
    $my_array = explode("||", $str);
    $my_array = array_filter($my_array);
    
    foreach ($my_array as $mine) {
      $my = explode("|", $mine);
      $new_array[$my[0]] = $my[1];
    }
    

    print_r($new_array);

    // Output

    Array
    (
        [a] => apple
        [b] => bat
        [c] => cat
        [d] => dog
    )