我有一个字符串,其中包含productID' s,其数量用逗号分隔
离。 2334(3),2335(15)
我怎么能比使用explode substr explode更容易把它变成一个数组呢?我对RegExp很可怕,但我认为你可以懒得捕捉变量?
像: $ a [2334] = 3
答案 0 :(得分:1)
您可以使用:
if (preg_match_all('/(\d+)\((\d+)\)/', '2334(3),2335(15)', $matches)) {
$output = array_combine ( $matches[1], $matches[2] );
print_r($output);
}
Array
(
[2334] => 3
[2335] => 15
)
答案 1 :(得分:1)
$sProducts = '2334(3),2335(15)';
$products = array();
$regex = '/(\d+)\((\d+\))/';
preg_match_all($regex, $sProducts, $matches);
$products = array_combine($matches[1], $matches[2]);
print_r($products);
输出:
Array ( [2334] => 3) [2335] => 15) )
答案 2 :(得分:1)
类似的东西:
$input = '2334(3),2335(15)';
//split your data into more manageable chunks
$raw_arr = explode(',', $input);
$processed_arr = array();
foreach( $raw_arr as $item ) {
$matches = array();
// simple regexes are less likely to go off the rails
preg_match('/(\d+)\((\d+)\)/', $item, $matches);
if( !empty($matches) ) {
$processed_arr[$matches[1]] = $matches[2];
} else {
// don't ignore the possibility of error
echo "could not process $item\n";
}
}