正则表达式组.在一组中提取尽可能少的参数


Regular expression group. Extract as few parameters in one group

我有字符串some-other/other/ram/1gb/2gb/other,并希望解析ram组,它必须捕获可重复的参数。(用于url过滤ram/1gb/2gb/4gb,表示ram组和捕获值数组(1gb, 2gb, 4gb))

我必须在正则表达式中更改什么以捕获一个参数组下的参数数组?现在我有:

$str = "some-other/other/ram/1gb/2gb/other";
$possible_values = implode('|', array('1gb','2gb','4gb','8gb','12gb','16gb','32gb'))
$compiled = "#(.*)ram/(?P<ram>{$possible_values})(.*)$#uD";
if(preg_match($compiled,$str,$matches){
var_dump($matches['ram'])
//output is string '1gb', but I want to see array('1gb', '2gb')
}

我必须改变什么?谢谢!

尝试:

$compiled = "#^(.*)ram/(?P<ram>(?:{$possible_values}/?)+)(/(?:.*))$#uD";

内部组匹配任何可能的值序列,分隔为/

preg_match不会返回重复操作符的数组。使用explode('/', $matches['ram'])分割

我猜这可能比你想象的要简单,这是我的5美分:

$ram = "some-other/other/ram/1gb/2gb/other";
if (preg_match('%/ram/%i', $ram)) {
    preg_match_all('/('d+gb)/i', $ram, $matches, PREG_PATTERN_ORDER);
}
 var_dump($matches[1]); 

输出:

array(2) {
  [0]=>
  string(3) "1gb"
  [1]=>
  string(3) "2gb"
}
演示:

http://ideone.com/jMoobu