1

I have the following string (taken from a user) in PHP "array" format.

array(
  array('age', '30', '>'),
  array(
    array('city', 'New Delhi'),
    array('city', 'New York')
  )
);

I wan't to convert this string to a PHP array without using eval (because I want to avoid its security risks). This is similar to doing json_decode. However, in this case the syntax is in PHP. Is this possible in a quick / easy way?

2
  • Can't you get it in a different, language-independent format? Because off the top of my head, I don't think there's a PHP array format parser in PHP (weird, innit? ;)). Unless there's already a library for it, I'd parse the string with the PHP tokenizer and build something that assembles the parsed tokens into a real array. That's a lot of work though if you could simply request the input to be JSON formatted (or something else). Commented Dec 7, 2011 at 6:31
  • The quick, easy way is to use eval Commented Dec 7, 2011 at 6:34

1 Answer 1

2

You could try this, but it will obviously fail in a lot of cases

$s = "array(
  array('age', '30', '>'),
  array(
    array('city', 'New Delhi'),
    array('city', 'New York')
  )
);
";
$rep = trim(str_replace(array('array(', ')', "\r", "\n", ' ', "'"), array('[', ']', '', '', '', '"'), $s), ';');
var_dump(json_decode($rep));
var_dump($rep);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.