4

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= ) 
4
  • php.net/manual/en/function.parse-url.php try something with this function Commented Aug 2, 2017 at 12:57
  • This is what I get with the parse_url() function : Array ( [path] => NAME=Marco_LOCATION=localhost_SECRET=fjsdgfsjfdskffuv=_ ) Commented Aug 2, 2017 at 13:16
  • @Alive to Die I did not downgrade your answer. Why would you do that to my question? Commented Aug 2, 2017 at 13:23
  • @Marco sorry did it accidentally. reverted back. Commented Aug 2, 2017 at 13:27

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0
$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...

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.