解析php中的数组字符串

时间:2015-06-18 23:53:15

标签: php arrays string parsing

如何解析数组字符串,以便获取变量

的值

示例字符串

$str = 'prices[holiday:waterpark][person:1_person]';

示例变量

$prices['holiday:waterpark']['person:1_person'] = 100;

我已尝试在像这样的

中使用variables.variable方式
$prices['holiday:waterpark']['person:1_person'] = 100;
$str = "prices\['holiday:waterpark'\]\['person:1_person'\]";
$str = str_replace('\\', '', $str);
echo $$str;

但那不起作用,我收到错误

"Undefined variable: $prices['holiday:waterpark']['person:1_person']"

1 个答案:

答案 0 :(得分:1)

试试这个

<?
    $prices['holiday:waterpark']['person:1_person'] = 100;
    $str = "prices\['holiday:waterpark'\]\['person:1_person'\]";
    $str = stripslashes($str);
    // be careful with passing $str from untrusted source
    // make necessary variable filtering before!
    echo eval('return $' . $str . ';');