如果允许使用多个 preg_match,这可能是一个解决方案:
$str = '[cpu]4[cpu] cores and [ram]16gb[ram][hdd]1TB[hdd]asdaddtgg[vga]2gb[vga]';
$arrResult = array();
preg_match_all('/(\[[A-Za-z0-9]+\][A-Za-z0-9]+\[[A-Za-z0-9]+\])/i', $str, $match,PREG_SET_ORDER);
if (is_array($match)) {
foreach ($match as $tmp) {
if (preg_match('/\[([A-Za-z0-9]+)\]([A-Za-z0-9]+)\[([A-Za-z0-9]+)\]/', $tmp[0], $matchkey)) {
$arrResult[$matchkey[1]] = $matchkey[2];
}
}
}
var_dump($arrResult);
结果:
array(4) {
'cpu' =>
string(1) "4"
'ram' =>
string(4) "16gb"
'hdd' =>
string(3) "1TB"
'vga' =>
string(3) "2gb"
}