Thursday, 30 August 2018

Read array from string php

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

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.

0 comments:

Post a Comment