将字符串转换为变量

时间:2012-08-27 13:32:52

标签: php

如何转换

$myvar = '[aaa](11,22,33,44,55)[bbb](1,2,3,4,5)';

进入那个

$arr_name[1] = 'aaa';
$arr_val[1] = '11,22,33,44,55';

$arr_name[2] = 'bbb';
$arr_val[2] = '1,2,3,4,5';

我应该使用哪些功能?

2 个答案:

答案 0 :(得分:3)

if(preg_match_all('/\[(.*?)\]\((.*?)\)/',$myvar,$matches)) {
    foreach($matches[0] as $k=>$v) {
        $arr_name[$k] = $matches[1][$k];
        $arr_val[$k] = $matches[2][$k];
    }
}

答案 1 :(得分:0)

您可以尝试使用正则表达式来提取密钥和密钥。变量,然后将它们插入数组:

$keys = array();
preg_match_all("/\[.+\]/", $myvar, $keys);

$values = array();
preg_match_all("/\(.+\)/", $myvar, $values);

$numKeys = count($keys);
$numVals = count($values);

$result = array();
foreach ($i = 0; $i < $numKeys; $i++) {
    if ($i < $numVals) {
        $result[trim($keys[$i], "[]")] = trim($values[$i], "()");
    }
}