Convert string into key-value array

I was looking for a function or solution, that would convert a string into associative array, i.e. respecting both keys and values. To be successfull, such function would have to operate on two delimiters. One for separating each key-value pair from surronding one. And second — for spliting keys from values. Which is, where PHP’s build-in explode function fails. Lucky I am, my two favorite uncles — Uncle Google and Uncle Stack Overflow — helped me in this case as well.

In particular, I was looking for something that will convert me string similar to this:


into array like this:

    [731554053263] => A
    [776531040016] => B
    [737453041595] => C
    [739188043063] => D
    [779465047076] => E

After googling a little bit, I’ve found this solution. After a slight modifications to it, I came with following code:

$matches = array();
$list = file_get_contents('imei.list');
preg_match_all('/(.*?)#s?(.*?)(rn|$)/', $list, $matches);
$headers = array_combine(array_map('trim', $matches[1]), $matches[2]);

echo('<pre>'.print_r($headers, TRUE).'</pre>');

Which, was, what I really needed.

BTW: If you need to change both delimiters, to suit this solution to your own needs, change regular expression used in preg_match_all function. Especially take a look at # (key-value separator in my example) and rn (lines or pairs separator).

This solution uses regular expressions and PHP’s preg_-familly function. Which are considered as one of the slowest in PHP. This is fine for me, as I’m using this function only once per each request. If you’re looking for something faster, look into this, this or this Stack Overflow articles. Or do some more googling.

Leave a Reply