Split file based on delimiters in php - what is the best way to use?

I am trying to parse a file using php, but I'm not sure if this is the best way to do this. A file consists of files such as:

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 the hash map, so ..

$inventory["saturn+5"] = "57";
$inventory["space+shuttle"] = "34";
and so on.

I do not know how to solve this.

I am trying to write a bit of regular expression to process a file to highlight fields, but I was not very lucky and I was wondering if I was trying to use a different approach using split()or explode().

+4
source share
4 answers

Here my approach uses regex.

$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
)
+2
source

:

<?php
echo '<pre>';
$str="saturn+5 57 space+shuttle 34 gemini 12 mercury 2 soyuz+tm 1";

//break it on space
$e=explode(' ',$str);

//reindex array to start from 1
array_unshift($e, "phoney");
unset($e[0]);

print_r($e);
$inventory=array();
foreach ($e as $k=>$v){

//detects odd key   
if(($k+2)%2==1) {

$inventory[$v]= $e[$k+1];

    }

}

print_r($inventory);

demo: http://codepad.viper-7.com/PN6K8m

:

Array
(
    [saturn+5] => 57
    [space+shuttle] => 34
    [gemini] => 12
    [mercury] => 2
    [soyuz+tm] => 1
)
+2

, :

<?

$foo = 'saturn+5 57 space+shuttle 34 gemini 12 mercury 2 soyuz+tm 1';
$foo_array = preg_split('/\s+/', $foo);

$hash = array();
for ($i = 0; $i < count($foo_array); $i++){
    $i % 2 ? null : $hash[$foo_array[$i]] = $foo_array[++$i];
}

print_r($hash);
?>

:

php foo.php
Array
(
    [saturn+5] => 57
    [space+shuttle] => 34
    [gemini] => 12
    [mercury] => 2
    [soyuz+tm] => 1
)
+2

This is actually pretty trivial with a regex:

preg_match_all("/  ([\w+]+)  \s  (\d+)  /x", $string, $m);
$assoc = array_combine($m[1], $m[2]);

You are just looking for a combination of alphanumeric characters \wand optional characters +, then a space, then a \ddecimal.

array_combine will provide you with an associative array.

+2
source

Source: https://habr.com/ru/post/1543494/


All Articles