我有字符串some-other/other/ram/1gb/2gb/other
,并想要解析必须捕获可重复参数的ram
组。 (它用于网址过滤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')
}
我必须改变什么?谢谢!
答案 0 :(得分:1)
尝试:
$compiled = "#^(.*)ram/(?P<ram>(?:{$possible_values}/?)+)(/(?:.*))$#uD";
内部组匹配可能值的任何序列,分隔为/
。
preg_match
不会为重复运算符返回数组。使用explode('/', $matches['ram'])
将其拆分。
答案 1 :(得分:0)
我想这可能比你想象的要容易,这是我的5美分:
$(document).ready(function() {
// when you keep DOM elements in variables is better to put $ in the beginning
var $module = $(".divCreate");
// faster than .find()
var $list = $(".listTag", $module);
// can not call 'on' with variable
//var $button = $(".divButton", $module);
// called through document since we need to handle dynamic added elements - check event delegation
$(document).on("click", ".divButton", function() {
$list.append("<div class='tag'>Tag</div>");
setTimeout(function() {
// some improvments
$(".tag", $list).last().addClass("tag-show");
}, 40);
// Just keep this if you have divButton attached to an anchor element
// Useful for preventing default behvaiour - in this case adding "#" to url
return false;
});
// Do not need to create the event inside that event
$(document).on("click", ".tag-show", function() {
// Since we use an element more than once is better to
// add it into a variable to avoid performance issues - js caches it and call the variable
var $el = $(this); // our needed 'this'
$el.removeClass("tag-show");
setTimeout(function() {
// 'this' here returns some properties of window (where setTimeout belongs), we need to call element cached above
//(the 'this' above contains what we need)
$el.remove();
}, 190);
});
});
<强>输出:强>
$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]);
<强>样本:强>