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:
 => A
 => B
 => C
 => D
 => 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), $matches);
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.