I am trying to parse a file using php but I am not sure of the best way to do it. The file consists of stuff like:
saturn+5 57 space+shuttle 34 gemini 12 mercury 2 soyuz+tm 1
What I'm trying to do is split it up and populate a hash map, so..
$inventory["saturn+5"] = "57";
$inventory["space+shuttle"] = "34";
and so on.
I don't know how to tackle this.
I am trying to write a bit of regex to process the file to separate out the fields but I'm not having much luck and was wondering if I should try using a different approach using split()
or explode()
.
Here's my approach using regular expression.
$data = 'saturn+5 57 space+shuttle 34 gemini 12 mercury 2 soyuz+tm 1';
$inventory = array();
preg_match_all('/(\S+) (\S+)/', $data, $matches);
foreach ($matches[1] as $index => $match) {
$inventory[$match] = $matches[2][$index];
}
print_r($inventory);
Output
Array
(
[saturn+5] => 57
[space+shuttle] => 34
[gemini] => 12
[mercury] => 2
[soyuz+tm] => 1
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With