Convert a String to Variable

后端 未结 9 2147
臣服心动
臣服心动 2020-12-01 05:43

I\'ve got a multidimensional associative array which includes an elements like

$data[\"status\"]
$data[\"response\"][\"url\"]
$data[\"entry\"][\"0\"][\"text\         


        
9条回答
  •  遥遥无期
    2020-12-01 06:11

    Quick and dirty:

    echo eval('return $'. $string . ';');
    

    Of course the input string would need to be be sanitized first.

    If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe.

    It does, however, make assumptions about the string format:

     'http://www.testing.com'
    );
    
    function extract_data($string) {
        global $data;
    
        $found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
        if (!$found_matches) {
                return null;
        }
    
        $current_data = $data;
        foreach ($matches[1] as $name) {
                if (key_exists($name, $current_data)) {
                        $current_data = $current_data[$name];
                } else {
                        return null;
                }
        }
    
        return $current_data;
    } 
    
    echo extract_data('data["response"]["url"]');
    ?>
    

提交回复
热议问题