简体   繁体   English

使用RegExp分隔字符串

[英]Separate string using RegExp

I have a string coming in that has productID's and their quantity separated by comma 我有一个字符串,其中有productID,其数量用逗号分隔

ex. 恩。 2334(3),2335(15) 2334(3),2335(15)

how could I turn this into an array easier than using explode substr explode? 我怎么能比使用explode substr explode更容易把它变成一个数组呢? I'm terrible with RegExp, but I think you can lazy capture the variables? 我对RegExp很糟糕,但我认为你可以懒得捕捉变量?

like: $a[2334] = 3 喜欢:$ a [2334] = 3

You can use: 您可以使用:

if (preg_match_all('/(\d+)\((\d+)\)/', '2334(3),2335(15)', $matches)) {
    $output = array_combine ( $matches[1], $matches[2] );
    print_r($output);   
}

OUTPUT: OUTPUT:

Array
(
    [2334] => 3
    [2335] => 15
)
$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);

Output: 输出:

Array ( [2334] => 3) [2335] => 15) )

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

Something like: 就像是:

$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";
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM