开发者

Convert string to array value in PHP

开发者 https://www.devze.com 2023-02-06 22:47 出处:网络
If I had an array such as: testarray = array(\'foo\'=>34, \'bar\'=>array(1, 2, 3)); How would I go about converting a string such as testarray[bar][0] to find the value its descri开发者_运维百

If I had an array such as:

testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));

How would I go about converting a string such as testarray[bar][0] to find the value its descri开发者_运维百科bing?


Well, you can do something like this (Not the prettiest, but far safer than eval)...:

$string = "testarray[bar][0]";

$variableBlock = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$regex = '/^('.$variableBlock.')((\[\w+\])*)$/';
if (preg_match($regex, $string, $match)) {
    $variableName = $match[1]; // "testarray"
    if (!isset($$variableName)) {
        //Error, the variable does not exist
        return null;
    } else {
        $array = $$variableName;
        if (preg_match_all('/\[(\w+)\]/', $match[2], $matches)) {
            foreach ($matches[1] as $match) {
                if (!is_array($array)) {
                    $array = null;
                    break;
                }
                $array = isset($array[$match]) ? $array[$match] : null;
            }
        }
        return $array;
    }
} else {
    //error, not in correct format
}


You could use PHP's eval function.

http://php.net/manual/en/function.eval.php

However, make absolutely sure the input is sanitized!

Cheers

0

精彩评论

暂无评论...
验证码 换一张
取 消