我有一个字符串,里面有productID,它们的数量用逗号隔开
例如。2334(3)、2335(15)
我怎么能比使用爆炸物质爆炸更容易把它变成一个数组呢?我在RegExp上做得很糟糕,但我认为你可以懒得捕捉变量吗?
相似:$a2334 =3
发布于 2014-03-11 21:15:42
您可以使用:
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
)发布于 2014-03-11 21:20:30
$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) )小提琴:http://phpfiddle.org/lite/code/k9g-057
发布于 2014-03-11 21:22:09
类似于:
$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";
}
}https://stackoverflow.com/questions/22336655
复制相似问题