Search code examples
phpsplittext-parsing

Parse a string with two different delimiters into an associative array


I have a string variable like the one below. I'm trying to split it into an array or even into separate variables for each element (change, day high etc.).

$a='last: 901.5001 @ 11:35am EST 11/10/2011 <br>change: -5.9999 <br>day high: 
921.50 <br>day low: 882.00 <br>open: 917.50 <br>volume: 808998';
echo $a;

Any ideas how I do this?


Solution

  • You could split on <br> first, then split on the first colon:

    $temp = explode("<br>",$a);
    $data = array();
    foreach ($temp as $item) {
       list($name, $value) = explode(":", $item, 2);
       $data[$name] = $value;
    }
    

    should output:

    Array
    (
       [last] => 901.5001 @ 11:35am EST 11/10/2011
       [change] => -5.9999
       [day high] => 921.50
       [open] => 882.00
       ... etc ...
    )