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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.