在PHP中将字符串解析为数组

时间:2012-08-31 09:42:27

标签: php arrays

我是PHP的新手,无法找到合适的答案。

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

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

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

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

在我正在研究的实际代码中,这不可能。另外,在我的实际代码中,数组是多维的,所以涉及字符替换的东西可能是不切实际的,但是如果它是最好的选择,我不会把它排除在外。

总而言之,在PHP中将字符串解析为数组的最佳方法是什么?

6 个答案:

答案 0 :(得分:8)

使用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代码。

答案 1 :(得分:5)

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

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

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

echo $parsed[1];

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

答案 2 :(得分:1)

eval()是邪恶的。它的性能很差,而且不安全

因此,如果您的阵列不那么复杂,请使用正则表达式

$subject = "array('Test','Blah','Blah2','Blah3')";
$pattern = "/'(.*?)'/";
preg_match_all($pattern, $subject, $matches);
echo "<pre>";print_r($matches[1]);

答案 3 :(得分: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);

答案 4 :(得分:0)

你可以写

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

eval( $strCreateArray );

答案 5 :(得分:0)

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

你有没有办法让这些数组格式化?对我来说没有任何意义可以像这样存储数组。序列化或json是更好的选择。