Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split file up based on delimiters in php - which is the best to use?

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().

like image 580
user3713442 Avatar asked Feb 12 '23 19:02

user3713442


1 Answers

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
)
like image 54
hwnd Avatar answered Feb 15 '23 07:02

hwnd