这是初始字符串:-
NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n
这是我的解决方案,虽然字符串末尾的“=”没有出现在数组中
$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);
这是我得到的结果:
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )
但我需要:
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv= )
最佳答案
可以使用preg_split的limit参数让它只分割一次
http://php.net/manual/en/function.preg-split.php
你应该改变
$result = preg_split ('/=/', $val);
到
$result = preg_split ('/=/', $val, 2);
希望对你有帮助
关于php - 如何从字符串中获取关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45461437/