A
A
Alexander Sharomet2019-02-08 17:19:38
PHP
Alexander Sharomet, 2019-02-08 17:19:38

How to properly parse a file?

Hello.
I have a file with the following data:

$base-color-primary:#3687ef;
$base-color-second:#fc665e;
$base-color-third:#b143b3;

At the output, I should get an associative array like this:
[
    'base-color-primary' => '#3687ef',
    'base-color-second'  => '#fc665e',
    'base-color-third'   => '#b143b3'
]

// $data - данные
preg_match_all('/\$(.*)\:/', $data, $arr); // Получаем значение от $ до : , получаем $base-color-primary:
for($v = 0;$v<count($arr[0]);$v++){
    $variables[$v] = trim(str_replace(array(':','$'),'',$arr[0][$v])); // Проходим по каждому значению и убираем $ и : , получаем base-color-primary  
}

I do the same and with the second values ​​I only get the value from # to ; (#3687ef)
And only then do I substitute all this into an array.
Can this be done in an easier way?
Thanks
All code
$var = array();
        for($v = 0;$v<count($arr[0]);$v++){
            $variables[$v] = trim(str_replace(array(':','$'),'',$arr[0][$v]));
        }
        for($i = 0; $i < count($variables);$i++){
            preg_match_all('/\#(.*)\;/', $data, $res);
            $var[$variables[$i]] = trim(strtok($res[1][0], ';'));
        }
        return $var;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2019-02-08
@sharomet

$text = file_get_contents('file.txt');

preg_match_all('~\$(.*):#(.*);~', $text, $m);
$a = array_combine($m[1], $m[2]);

print_r($a);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question