php - 如何从字符串中获取关联数组?

标签 php arrays

这是初始字符串:-

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/

相关文章:

arrays - Firebase/Firestore 是否按存储顺序返回数组?

php - 简化: mysqli num_rows not working

php - 支持 Git 的 Mac OS X PHP IDE

php_excel : Customize the heigth row

javascript - JavaScript 中的动态数组

ios - 在 UITableView 中选择具有过滤结果的行时,如何获取实际的数组索引值? swift

Java:方法返回类型为数组错误

.net - 数组与列表<T> : When to use which?

javascript - Opencart - 检查用户是否登录并重定向到帐户页面

php - 表格每一行的非法字符串偏移量 'Data_length'/'Index_length'