I have an array of user inputs ($atts) as key=>value pairs. Some of the values could be written as an array expression, such as:
\'setting\' => \'array(50,25)
Use the tokenizer:
function stringToArray($str) {
$array = array();
$toks = token_get_all("
The above will work only for literals. Passing a variable, a constant, an expression, a nested array or a malformed array declaration will return null:
stringToArray('array(1,2)'); // works
stringToArray('array(1,2.4)'); // works
stringToArray('array("foo",2)'); // works
stringToArray('array(\'hello\',2)'); // works
stringToArray('array()'); // works
stringToArray('array(1,2 + 3)'); // returns null
stringToArray('array(1,2 + 3)'); // returns null
stringToArray('array("foo"."bar")'); // returns null
stringToArray('array(array("hello"))'); // returns null
stringToArray('array($a,$b)'); // returns null
stringToArray('array(new bar)'); // returns null
stringToArray('array(SOME_CONST)'); // returns null
stringToArray('hello'); // returns null
You can also use the following to check if your string is an array expression or not:
function isArrayExpression($str) {
$toks = token_get_all("
You can always tweak it to your needs. Hope this helps.