PHP: How to turn a string that contains an array expression in an actual array?

后端 未结 4 616
广开言路
广开言路 2021-01-25 09:04

I have an array of user inputs ($atts) as key=>value pairs. Some of the values could be written as an array expression, such as:

\'setting\' => \'array(50,25)         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 09:57

    function stringToArray($string) {
            $string = "return " . $string . ";";
            if (function_exists("token_get_all")) {//tokenizer extension may be disabled
                $php = "";
                $tokens = token_get_all($php);
                            foreach ($tokens as $token) {
                    $type = $token[0];
                    if (is_long($type)) {
                        if (in_array($type, array(
                                T_OPEN_TAG, 
                                T_RETURN, 
                                T_WHITESPACE, 
                                T_ARRAY, 
                                T_LNUMBER, 
                                T_DNUMBER,
                                T_CONSTANT_ENCAPSED_STRING, 
                                T_DOUBLE_ARROW, 
                                T_CLOSE_TAG,
                                T_NEW,
                                T_DOUBLE_COLON
                                ))) {
                            continue;
                        }
    
    
                        exit("For your security, we stoped data parsing at '(" . token_name($type) . ") " . $token[1] . "'.");
                    }
                }
            }
    
            return eval($string);
        }
    
    $a='array(10,20)';
    print_r(stringToArray($a));
    

提交回复
热议问题