可靠地将包含 PHP 数组信息的字符串转换为数组 [重复]

2024-03-05

可能的重复:
模拟 php 数组语言构造或使用正则表达式解析? https://stackoverflow.com/questions/3267951/simulate-php-array-language-construct-or-parse-with-regexp

假设我有字符串

$str = "array(1,3,4),array(array(4,5,6)),'this is a comma , inside a string',array('asdf' => 'lalal')";

我尝试用逗号将其分解为数组,以便所需的最终结果是

$explode[0] =  array(1,3,4);
$explode[1] = array(array(4,5,6));
$explode[2] = 'this is a comma , inside a string';
$explode[3] = array('asdf' => 'lalal');

只是打电话explode(',',$str)不会削减它,因为这些块中也有逗号......

即使所需块内有逗号,有没有办法可靠地分解它


即使所需块内有逗号,有没有办法可靠地分解它?

PHP默认情况下不提供这样的功能。然而,你的字符串中有一个 PHP 的紧凑子集,PHP 在这里提供了一些工具:PHP 分词器 http://www.php.net/manual/en/function.token-get-all.php and a PHP解析器 http://php.net/manual/en/function.eval.php.

因此,您的字符串规范可以创建一个辅助函数,根据允许的标记验证输入,然后解析它:

$str = "array(1,3,4),array(array(4,5,6)),'this is a comma , inside a string', array('asdf' => 'lalal')";

function explode_string($str)
{
    $result = NULL;
    
    // validate string
    $isValid = FALSE;
    $tokens = token_get_all(sprintf('<?php %s', $str));
    array_shift($tokens);
    $valid = array(305, 315, 358, 360, 371, '(', ')', ',');
    foreach($tokens as $token)
    {
        list($index) = (array) $token;
        if (!in_array($index, $valid))
        {
            $isValid = FALSE;
            break;
        }
    }
    if (!$isValid)
        throw new InvalidArgumentException('Invalid string.');
    
    // parse string
    $return = eval(sprintf('return array(%s);', $str));

    return $return;
}

echo $str, "\n";

$result = explode_string($str);

var_dump($result);

使用的代币是:

T_LNUMBER (305)
T_CONSTANT_ENCAPSED_STRING (315)
T_DOUBLE_ARROW (358)
T_ARRAY (360)
T_WHITESPACE (371)

令牌索引号可以指定为代币名称 https://www.php.net/manual/en/tokens.php通过使用token_name https://www.php.net/manual/en/function.token-name.php.

这给了你(Demo http://codepad.viper-7.com/gTHrDk):

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 4
        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 6
                )

        )

    [2] => this is a comma , inside a string
    [3] => Array
        (
            [asdf] => lalal
        )

)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

可靠地将包含 PHP 数组信息的字符串转换为数组 [重复] 的相关文章

随机推荐