I have a string that contains associative array like that
$string = "['key1'=>'value1','key2'=>'value2','key3'=>'value3']";
and I want to convert it to an associative array so i can loop through it.
is there any way to do it ?
Thanks in advance .
Very simple way is convert that string to json and decode
$string = str_replace(["'", '=>', '[', ']'], ['"', ':', '{', '}'], $string);
print_r(json_decode($string, true));
You can use preg_match_all
Like so:
$string = "['key1'=>'value1','key2'=>'value2','key3'=>'value3']";
preg_match_all("/'(?P<key>[-\w]+)'\s*=\>\s*'(?P<value>[-\w]+)'/", $string, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => 'key1'=>'value1'
[1] => 'key2'=>'value2'
[2] => 'key3'=>'value3'
)
[key] => Array
(
[0] => key1
[1] => key2
[2] => key3
)
[1] => Array
(
[0] => key1
[1] => key2
[2] => key3
)
[value] => Array
(
[0] => value1
[1] => value2
[2] => value3
)
[2] => Array
(
[0] => value1
[1] => value2
[2] => value3
)
)
See it live here
One note is that [-\\w]+
matchs az
, AZ
, 0-9
, -
and _
, so this should be the format for both the keys and values. You can of course adjust the Regx to your needs.
Now if you want to put them in a more usable format you can add this:
$output = array_combine($matches['key'],$matches['value']);
Output
Array
(
[key1] => value1
[key2] => value2
[key3] => value3
)
One note I should say, is this will not work for nested arrays, for that you need something a bit more advanced.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.