dongtun3259 2018-07-07 10:48
浏览 43
已采纳

我试图在PHP中将字符串转换为数组,因为我有下面给出的字符串

I had tried explode function but it's not giving an output which i want.

Here is my code and explanation:

    {
    refresh_token: "xxxx",

    access_token: "xxxx",

    expires_in: 21600,
    }

I have this value as string and i want to convert this refresh_token as key in array and "xxxx" as value in array.

I had tried with explode function but it gives new keys like [0]=>"refresh_token".

  • 写回答

5条回答 默认 最新

  • douxin20081125 2018-07-07 11:09
    关注

    explode() is not suited for this job. With that string format, you will need to write a custom function. Assuming the values do not contain commas and the last value in your object always ends with a comma just like the others, something like this will do:

    function parse_value_string($string) {
        preg_match_all('/([a-z_]+):\s+(.*),/', $string, $matches);
    
        return array_combine($matches[1], array_map(function($val) {
            return trim($val, '"');
        }, $matches[2]));
    }
    
    $test = '{
        refresh_token: "xxxx",
    
        access_token: "xxxx",
    
        expires_in: 21600,
    }';
    
    $values = parse_value_string($test);
    
    print_r($values);
    /*
    Array
    (
        [refresh_token] => xxxx
        [access_token] => xxxx
        [expires_in] => 21600
    )
    */
    

    Demo

    Depending on your actual data, you're probably going to run into issues with this approach. Your source string is actually really close to regular JSON. If you drop the comma after the last value and wrap your data keys in quotation marks, you can use PHP's native JSON support to parse it:

    $test = '{
        "refresh_token": "xxxx",
    
        "access_token": "xxxx",
    
        "expires_in": 21600
    }';
    
    $values = json_decode($test, true);
    
    print_r($values);
    /*
    Array
    (
        [refresh_token] => xxxx
        [access_token] => xxxx
        [expires_in] => 21600
    )
    */
    

    Demo

    So, if you can tweak the source of your string to generate valid JSON instead of this custom string, your life will suddenly become a whole lot easier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥15 QFILHelper怎么恢复全字库,提示进程已完成,只能恢复分区文件
  • ¥150 求 《小魔指》街机游戏机整合模拟软件
  • ¥20 你好,我想问下easyExcel下拉多选,或者复选框可以实现吗
  • ¥20 双非跨考工科哪个专业和方向就业前景好?