Search code examples
phparraysstringexplodetext-parsing

Convert formatted lines of delimited text into an associative array


I have a string of key->value pairs in the following colon-separated format:

MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!

How do I get an associative array such that arr['From'] = "Tim Lincecum", etc.?

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?


Solution

  • Since I did a good guess in comments - I think i need to repeat it here as an answer:

    There is a newlines between parameters, so with

    $parameters_pairs = explode("\r\n", $parameters_string);
    

    you can split it into the name-value pairs, separated with colon.