且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串转换为变量

更新时间:2023-02-03 09:47:49

又快又脏:

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

当然,输入字符串需要先清理.

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

如果你不喜欢快速和肮脏......那么这也可以,它不需要 eval,这甚至让我感到畏缩.

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:

<?php
$data['response'] = array(
    'url' => '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"]');
?>