5

我是 PHP 新手,找不到正确的答案。

$whatever = "array('Test','Blah')";
echo $parsed[2]; //This will be "Blah"

我想创建一个名为的变量,该变量$parsed包含$whatever的值,但作为有效数组而不是字符串。

我知道我可以通过删除它周围的引号来创建数组,如下所示:

$whatever = array('Test','Blah');

但是,在我正在处理的实际代码中,这是不可能的。此外,在我的实际代码中,数组是多维的,因此涉及字符替换的东西可能是不切实际的,但是我不排除它是否是最佳选择。

综上所述,在 PHP 中将字符串解析为数组的最佳方法是什么?

4

6 回答 6

12

使用eval函数: http: //php.net/manual/en/function.eval.php

$whatever = "array('Test','Blah')";
$parsed = eval("return " . $whatever . ";");
echo $parsed[1]; //This will be "Blah"

仔细检查$whatever变量内容,因为可以执行任何 PHP 代码。

于 2012-08-31T09:44:46.763 回答
5

更安全的方式(没有评估)是:

$whatever = "array('Test','Blah')";

$search = array("array", "(", ")", "'");
$parsed = explode(',',str_replace($search, '', $whatever));

echo $parsed[1];

这将删除所有不必要的文本,然后将使用逗号分隔符分解字符串。

于 2012-08-31T09:54:07.143 回答
1

eval()是邪恶的。性能差,不安全

因此,如果您的数组没有那么复杂,请使用正则表达式

$subject = "array('Test','Blah','Blah2','Blah3')";
$pattern = "/'(.*?)'/";
preg_match_all($pattern, $subject, $matches);
echo "<pre>";print_r($matches[1]);
于 2012-08-31T10:01:53.047 回答
1

这是我一直在做的事情。目前还没有单元测试,但它似乎工作得很好。我不支持在数组结构中使用函数、对象实例化、条件等。我不想为我的用例支持这些。但是请随意添加您需要的任何功能。

/**
 * A class used convert string representations or php arrays to an array without using eval()
 */
class ArrayTokenScanner
{
    /** @var array  */
    protected $arrayKeys = [];

    /**
     * @param string $string   e.g. array('foo' => 123, 'bar' => [0 => 123, 1 => 12345])
     *
     * @return array
     */
    public function scan($string)
    {
        // Remove whitespace and semi colons
        $sanitized = trim($string, " \t\n\r\0\x0B;");
        if(preg_match('/^(\[|array\().*(\]|\))$/', $sanitized)) {
            if($tokens = $this->tokenize("<?php {$sanitized}")) {
                $this->initialize($tokens);
                return $this->parse($tokens);
            }
        }

        // Given array format is invalid
        throw new InvalidArgumentException("Invalid array format.");
    }

    /**
     * @param array $tokens
     */
    protected function initialize(array $tokens)
    {
        $this->arrayKeys = [];
        while($current = current($tokens)) {
            $next = next($tokens);
            if($next[0] === T_DOUBLE_ARROW) {
                $this->arrayKeys[] = $current[1];
            }
        }
    }

    /**
     * @param array $tokens
     * @return array
     */
    protected function parse(array &$tokens)
    {
        $array = [];
        $token = current($tokens);
        if(in_array($token[0], [T_ARRAY, T_BRACKET_OPEN])) {

            // Is array!
            $assoc = false;
            $index = 0;
            $discriminator = ($token[0] === T_ARRAY) ? T_ARRAY_CLOSE : T_BRACKET_CLOSE;
            while($token = $this->until($tokens, $discriminator)) {


                // Skip arrow ( => )
                if(in_array($token[0], [T_DOUBLE_ARROW])) {
                    continue;
                }

                // Reset associative array key
                if($token[0] === T_COMMA_SEPARATOR) {
                    $assoc = false;
                    continue;
                }

                // Look for array keys
                $next = next($tokens);
                prev($tokens);
                if($next[0] === T_DOUBLE_ARROW) {
                    // Is assoc key
                    $assoc = $token[1];
                    if(preg_match('/^-?(0|[1-9][0-9]*)$/', $assoc)) {
                        $index = $assoc = (int) $assoc;
                    }
                    continue;
                }

                // Parse array contents recursively
                if(in_array($token[0], [T_ARRAY, T_BRACKET_OPEN])) {
                    $array[($assoc !== false) ? $assoc : $this->createKey($index)] = $this->parse($tokens);
                    continue;
                }

                // Parse atomic string
                if(in_array($token[0], [T_STRING, T_NUM_STRING, T_CONSTANT_ENCAPSED_STRING])) {
                    $array[($assoc !== false) ? $assoc : $this->createKey($index)] = $this->parseAtomic($token[1]);
                }

                // Parse atomic number
                if(in_array($token[0], [T_LNUMBER, T_DNUMBER])) {

                    // Check if number is negative
                    $prev = prev($tokens);
                    $value = $token[1];
                    if($prev[0] === T_MINUS) {
                        $value = "-{$value}";
                    }
                    next($tokens);

                    $array[($assoc !== false) ? $assoc : $this->createKey($index)] = $this->parseAtomic($value);
                }

                // Increment index unless a associative key is used. In this case we want too reuse the current value.
                if(!is_string($assoc)) {
                    $index++;
                }
            }

            return $array;
        }
    }

    /**
     * @param array $tokens
     * @param int|string $discriminator
     *
     * @return array|false
     */
    protected function until(array &$tokens, $discriminator)
    {
        $next = next($tokens);
        if($next === false or $next[0] === $discriminator) {
            return false;
        }

        return $next;
    }

    protected function createKey(&$index)
    {
        do {
            if(!in_array($index, $this->arrayKeys, true)) {
                return $index;
            }
        } while(++$index);
    }

    /**
     * @param $string
     * @return array|false
     */
    protected function tokenize($string)
    {
        $tokens = token_get_all($string);
        if(is_array($tokens)) {

            // Filter tokens
            $tokens = array_values(array_filter($tokens, [$this, 'accept']));

            // Normalize token format, make syntax characters look like tokens for consistent parsing
            return $this->normalize($tokens);

        }

        return false;
    }

    /**
     * Method used to accept or deny tokens so that we only have to deal with the allowed tokens
     *
     * @param array|string $value    A token or syntax character
     * @return bool
     */
    protected function accept($value)
    {
        if(is_string($value)) {
            // Allowed syntax characters: comma's and brackets.
            return in_array($value, [',', '[', ']', ')', '-']);
        }
        if(!in_array($value[0], [T_ARRAY, T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_ARROW, T_STRING, T_NUM_STRING, T_LNUMBER, T_DNUMBER])) {
            // Token did not match requirement. The token is not listed in the collection above.
            return false;
        }
        // Token is accepted.
        return true;
    }

    /**
     * Normalize tokens so that each allowed syntax character looks like a token for consistent parsing.
     *
     * @param array $tokens
     *
     * @return array
     */
    protected function normalize(array $tokens)
    {
        // Define some constants for consistency. These characters are not "real" tokens.
        defined('T_MINUS')           ?: define('T_MINUS',           '-');
        defined('T_BRACKET_OPEN')    ?: define('T_BRACKET_OPEN',    '[');
        defined('T_BRACKET_CLOSE')   ?: define('T_BRACKET_CLOSE',   ']');
        defined('T_COMMA_SEPARATOR') ?: define('T_COMMA_SEPARATOR', ',');
        defined('T_ARRAY_CLOSE')     ?: define('T_ARRAY_CLOSE',     ')');

        // Normalize the token array
        return array_map( function($token) {

            // If the token is a syntax character ($token[0] will be string) than use the token (= $token[0]) as value (= $token[1]) as well.
            return [
                0 => $token[0],
                1 => (is_string($token[0])) ? $token[0] : $token[1]
            ];

        }, $tokens);
    }

    /**
     * @param $value
     *
     * @return mixed
     */
    protected function parseAtomic($value)
    {
        // If the parameter type is a string than it will be enclosed with quotes
        if(preg_match('/^["\'].*["\']$/', $value)) {
            // is (already) a string
            return $value;
        }

        // Parse integer
        if(preg_match('/^-?(0|[1-9][0-9]*)$/', $value)) {
            return (int) $value;
        }

        // Parse other sorts of numeric values (floats, scientific notation etc)
        if(is_numeric($value)) {
            return  (float) $value;
        }

        // Parse bool
        if(in_array(strtolower($value), ['true', 'false'])) {
            return ($value == 'true') ? true : false;
        }

        // Parse null
        if(strtolower($value) === 'null') {
            return null;
        }

        // Use string for any remaining values.
        // For example, bitsets are not supported. 0x2,1x2 etc
        return $value;
    }
}

使用示例:

$tokenScanner = new ArrayTokenScanner();
$array = $tokenScanner->scan('[array("foo" => -123, "foobie" => "5x2", "bar" => \'456\', 111 => 12, "bar", ["null" => null], "bool" => false), 123 => E_ERROR];');
$arrayExport = preg_replace('/[\s\t]+/', ' ', var_export($array, true));
echo stripslashes($arrayExport) . PHP_EOL;
$array2 = $tokenScanner->scan('[array("foo" => 123, "foobie" => "5x2", "bar" => \'456\', 111 => 12, "bar", ["null" => null], "bool" => false), 123 => E_ERROR];');
$arrayExport = preg_replace('/[\s\t]+/', ' ', var_export($array, true));
echo stripslashes($arrayExport);
于 2015-06-14T19:14:09.177 回答
0

你可以写

$strCreateArray = "$whatever = " . "array('Test','Blah')" . ";";

eval( $strCreateArray );
于 2012-08-31T09:45:11.453 回答
0

如果 eval 不是一个选项。根据数组是否始终具有相同的格式(从不多维),使用替换函数删除array()所有引号。然后在逗号上做一个字符串爆炸。

有没有办法不能为这些数组设置这种格式?像这样存储数组对我来说毫无意义。序列化或 json 是更好的选择。

于 2012-08-31T09:51:09.737 回答