Before I say anything about using eval()
, read this stackoverflow post.
As Yazmat mentioned, you could use eval()
if you're very sure that nobody could inject code into this, and use a regex of ([a-zA-Z0-9]+)\s*=\s*
replaced with "$1" =>
to change your code to be PHP array compliant:
<?php
$strVar = 'array(a=1, b=2, c=array(ca=23, cb=45),d=array(da=342, db=array(dba=3154, dbb=8746), dc=765),e=8)';
$arrValues = array();
$phpCompliantStrVar = preg_replace('/([a-zA-Z0-9]+)\s*=\s*/', '"$1" => ', $strVar) . ';';
//string(157) "array("a" => 1, "b" => 2, "c" => array("ca" => 23, "cb" => 45),"d" => array("da" => 342, "db" => array("dba" => 3154, "dbb" => 8746), "dc" => 765),"e" => 8);"
//Beware of the evilness that eval can cause! It will suck out your soul if overdone.
eval('$arrValues = ' . $phpCompliantStrVar);
print_r($arrValues);
/*
Array
(
[a] => 1
[b] => 2
[c] => Array
(
[ca] => 23
[cb] => 45
)
[d] => Array
(
[da] => 342
[db] => Array
(
[dba] => 3154
[dbb] => 8746
)
[dc] => 765
)
[e] => 8
)
*/
?>
DEMO
Current limitations:
- It will ONLY work if your values in the array are all numbers - else you need to change the regex.