首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用RegExp分离字符串

使用RegExp分离字符串
EN

Stack Overflow用户
提问于 2014-03-11 21:08:02
回答 3查看 42关注 0票数 1

我有一个字符串,里面有productID,它们的数量用逗号隔开

例如。2334(3)、2335(15)

我怎么能比使用爆炸物质爆炸更容易把它变成一个数组呢?我在RegExp上做得很糟糕,但我认为你可以懒得捕捉变量吗?

相似:$a2334 =3

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-11 21:15:42

您可以使用:

代码语言:javascript
运行
复制
if (preg_match_all('/(\d+)\((\d+)\)/', '2334(3),2335(15)', $matches)) {
    $output = array_combine ( $matches[1], $matches[2] );
    print_r($output);   
}

产出:

代码语言:javascript
运行
复制
Array
(
    [2334] => 3
    [2335] => 15
)
票数 1
EN

Stack Overflow用户

发布于 2014-03-11 21:20:30

代码语言:javascript
运行
复制
$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);

输出:

代码语言:javascript
运行
复制
Array ( [2334] => 3) [2335] => 15) )

小提琴:http://phpfiddle.org/lite/code/k9g-057

票数 1
EN

Stack Overflow用户

发布于 2014-03-11 21:22:09

类似于:

代码语言:javascript
运行
复制
$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";
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22336655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档