使用正则表达式提取URL参数-重复捕获组 [英] Extract URL parameters with regex - repeating a capture group
问题描述
我正在尝试通过正则表达式提取URL参数,并且非常接近使其能够正常工作.我什至知道问题是什么:我的正则表达式绊倒了重复的捕获组.但是我根本不知道如何解决它.
I'm attempting to extract the URL parameters via regex and am sooo close to getting it to work. I even know what the problem is: my regex is stumbling on repeated capture groups. But I simply cannot figure out how to fix it.
语言是PHP.
我的URL看起来像下面的URL.它可以没有参数,只有一个或多个:
My URL looks something like the one below. It can have no parameters, just one or multiple:
member.php?action=bla&arg=2&test=15&schedule=16
我的正则表达式如下:
member\.php((?:[\?|&](\w*)=(\w*))*)
我的捕获组最终成为:
1. action=bla&arg=2&test=15&schedule=16
2. schedule
3. 16
我无法弄清楚如何分别捕获所有参数.我是否只需要安定第一个俘虏组并自己爆炸就可以了?如果我可以在一个正则表达式中完成所有工作,那将对我而言更加优雅.
I cannot figure out how to capture all the parameters individually. Will I just have to settle for the first capture group and explode it myself? It would be much more elegant for my purposes if I can do all the work inside one regex.
推荐答案
try:
<?php
$str="member.php?action=bla&arg=2&test=15&schedule=16#test";
preg_match_all('/([^?&=#]+)=([^&#]*)/',$str,$m);
print_r($m);
//combine the keys and values onto an assoc array
$data=array_combine( $m[1], $m[2]);
print_r($data);
?>
这篇关于使用正则表达式提取URL参数-重复捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!