1

I have a string like this

$php_string = '$user["name"] = "Rahul";$user["age"] = 12;$person["name"] = "Jay";$person["age"] = 12;';

or like this

 $php_string = '$user = array("name"=>"Rahul","age"=>12);$person= array("name"=>"Jay","age"=>12);';

I need to get the array from the string ,

Expected result is

print_r($returned);

Array
(
    [name] => Rahul
    [age] => 12
)

Please note that there may be other contents on the string including comments,other php codes etc

12
  • 1
    Seems like a case for eval(), but only if you're sure this is the only way. Commented Nov 12, 2012 at 8:35
  • @Jack i do not want to execute the script , Commented Nov 12, 2012 at 8:37
  • Anything you've tried so far? Commented Nov 12, 2012 at 8:37
  • 1
    @xbonez like others suggested i tried to use eval , but it is a overkill , i tried to read the contents by line by line but the problem is that php have many formats for declaring arrays ..i was expecting a reg based one..which i dnt know anything .. Commented Nov 12, 2012 at 8:39
  • 1
    @Red Where does the string come from? Code in variables is typically just bad design. Commented Nov 12, 2012 at 8:40

2 Answers 2

2

Instead of relying on some magical regular expression, I would go a slightly easier route and use token_get_all() to tokenize the string and create a very basic parser that can create the necessary structures based on both array construction methods.

I don't think many people have rolled this themselves but it's likely the most stable solution.

Sign up to request clarification or add additional context in comments.

Comments

1

use a combination of eval and preg_match_all like so:

if(preg_match_all('/array\s*\(.*\)/U', $php_string, $arrays)){
    foreach($arrays as $array){
        $myArray = eval("return {$array};");
        print_r($myArray);
    }
}

That will work as long as your array doesn't contain ) but can be modified further to handle that case

or as Jack suggests use token_get_all() like so:

$tokens = token_get_all($php_string);
if(is_array($tokens)){
    foreach($tokens as $token){
        if($token[0] != T_ARRAY)continue;
        $myArray = eval("return {$token[1]};");
        print_r($myArray);
    }
}

3 Comments

But i think that eval will execute the script ,there may be some other codes too , so a string based operation needed.
you can refine the regular expression above to allow ( and ) and it should work for you
Thanks for the start , i will try to modify the codes and will post a redefined one ,especially for PHP5'S new array methods.

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.