我试图在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".

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.

you can use the PHP json_decode function as it is a JSON string format. For example : $encodedJson = json_decode('{ refresh_token: "xxxx", access_token: "xxxx", expires_in: 21600, }'); $encodedJson->access_token will give you the xxxx value

use str_split(); that should work

Unquoted keys in otherwise kosher-PHP json, you should just wrap those in quotes if possible, then you can just cast to an array: $x = (array) json_decode ( '{ "refresh_token": "xxxx", "access_token": "xxxx", "expires_in": 21600, }' );

If that's not possible higher up in the code, you can just use some string hackery to coerece it: $x = (array) json_decode( str_replace( [ ' ' , ':' , ',' , '{' , '}' ], [ '', '":', ',"' , '{"' , '"}' ],
'{refresh_token:"xxxx",access_token: "xxxx",expires_in: 21600}' ) );

I didn't actually check this code Also, this is ugly AF

just use json_decode function, but remember to check the validity of your string, for example in your string the last comma should be deleted and keys should be surrounded by double quotes.

enter image description here