Possible Duplicate:
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)
不会削减它,因为这些 block 中也有逗号...
有没有办法可靠地分解这个,即使在所需的 block 中有逗号
最佳答案
is there a way to explode this reliably even if there is commas inside the desired chunks?
PHP默认不提供这样的功能。然而,您的字符串中有一个紧凑的 PHP 子集,PHP 在这里提供了一些工具:A PHP tokenizer和一个PHP parser .
因此,您的字符串规范可以创建一个辅助函数,根据允许的标记验证输入,然后解析它:
$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);
使用的 token 是:
T_LNUMBER (305)
T_CONSTANT_ENCAPSED_STRING (315)
T_DOUBLE_ARROW (358)
T_ARRAY (360)
T_WHITESPACE (371)
token 索引号可以为 token name通过使用 token_name
.
这给你( Demo ):
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
)
)
关于php - 可靠地将包含 PHP 数组信息的字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7873354/