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

后端 未结 4 662
广开言路
广开言路 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:36

    Use the tokenizer:

    function stringToArray($str) {
        $array = array();
        $toks = token_get_all("

    The above will work only for literals. Passing a variable, a constant, an expression, a nested array or a malformed array declaration will return null:

    stringToArray('array(1,2)');              // works
    stringToArray('array(1,2.4)');            // works
    stringToArray('array("foo",2)');          // works
    stringToArray('array(\'hello\',2)');      // works
    stringToArray('array()');                 // works
    stringToArray('array(1,2 + 3)');          // returns null
    stringToArray('array(1,2 + 3)');          // returns null
    stringToArray('array("foo"."bar")');      // returns null
    stringToArray('array(array("hello"))');   // returns null
    stringToArray('array($a,$b)');            // returns null
    stringToArray('array(new bar)');          // returns null
    stringToArray('array(SOME_CONST)');       // returns null
    stringToArray('hello');                   // returns null
    

    You can also use the following to check if your string is an array expression or not:

    function isArrayExpression($str) {
        $toks = token_get_all("

    You can always tweak it to your needs. Hope this helps.

提交回复
热议问题