Marco
Marco

Reputation: 644

How to get an associative array from a string?

This is the initial string:-

NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n

This is my solution although the "=" in the end of the string does not appear in the array

$env = file_get_contents(base_path() . '/.env');

    // Split string on every " " and write into array
    $env = preg_split('/\s+/', $env);

    //create new array to push data in the foreach
    $newArray = array();

    foreach($env as $val){

        // Split string on every "=" and write into array
        $result = preg_split ('/=/', $val);

        if($result[0] && $result[1])
        {
            $newArray[$result[0]] = $result[1];
        }

    }

    print_r($newArray);

This is the result I get:

Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )

But I need :

Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv= )

Upvotes: 4

Views: 439

Answers (3)

Gergely Lukacsy
Gergely Lukacsy

Reputation: 3074

You can also use parse_str to parse URL syntax-like strings to name-value pairs.

Based on your example:

$newArray = [];

$str = file_get_contents(base_path() . '/.env');
$env = explode("\n", $str);

array_walk(
    $env,
    function ($i) use (&$newArray) {
        if (!$i) { return; }
        $tmp = [];
        parse_str($i, $tmp);
        $newArray[] = $tmp;
    }
);

var_dump($newArray);

Of course, you need to put some sanity check in the function since it can insert some strange stuff in the array like values with empty string keys, and whatnot.

Upvotes: 0

Werner
Werner

Reputation: 449

$string    = 'NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n';
$strXlate  = [ 'NAME='     => '"NAME":"'      ,
               'LOCATION=' => '","LOCATION":"', 
               'SECRET='   => '","SECRET":"'  ,
               '\n'        => ''               ];
$jsonified = '{'.strtr($string, $strXlate).'"}';
$array     = json_decode($jsonified, true);

This is based on 1) translation using strtr(), preparing an array in json format and then using a json_decode which blows it up nicely into an array...

Same result, other approach...

Upvotes: 0

Dimitris Filippou
Dimitris Filippou

Reputation: 809

You can use the limit parameter of preg_split to make it only split the string once

http://php.net/manual/en/function.preg-split.php

you should change

$result = preg_split ('/=/', $val);

to

$result = preg_split ('/=/', $val, 2);

Hope this helps

Upvotes: 2

Related Questions