将字符串(采用数组格式)转换为php中的数组


Convert a string (is in an array format) to array in php

在我的项目中,我必须转换一个数组格式的字符串:

$str = "array(array('text', 'Video Code', 0, 'videoCode', '', 'Paste the youtube Video Code'))";

有没有办法把它转换成一个数组,比如:

$array = array(array('text', 'Video Code', 0, 'videoCode', '', 'Paste the youtube Video Code'));

注:数组可能超过10维。

// if format of the string is like
$str = "array(array('text', 'Video Code', 0, 'videoCode', '', 'Paste the youtube Video Code'))";
// Make json format from it
$str = str_replace(['array(', ')', "'"], ['[',']', '"'], $str);
// And decode
print_r(json_decode($str, true));

结果

Array
(
    [0] => Array
        (
            [0] => text
            [1] => Video Code
            [2] => 0
            [3] => videoCode
            [4] => 
            [5] => Paste the youtube Video Code
        )
)

您可以使用eval,但不建议在公共数据上使用。

$str = "'$arr = array(array('text', 'Video Code', 0, 'videoCode', '', 'Paste the youtube Video Code'));";
eval($str);
print_r($arr);

来自PHP手册:

小心eval()语言构造非常危险,因为它允许执行任意PHP代码。因此,不鼓励使用它。如果您已经仔细验证,除了使用此构造时,请特别注意不要传递任何用户在没有事先正确验证的情况下向其提供数据。

试试这个:

$str = "array(array('text', 'Video Code', 0, 'videoCode', '', 'Paste the youtube Video Code'))";
$str = trim($str,"array(");
$str = trim($str,")");
$arr = explode(",",$str);
$arr_final = array();
$arr_final[] = $arr;
print '<pre>';print_r($arr_final);