Extract URL parameters with regex - repeating a ca

2020-04-11 14:33发布

问题:

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.

Language is PHP.

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

My regex looks like this:

member\.php((?:[\?|&](\w*)=(\w*))*)

And my capture groups end up being:

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.

回答1:

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);
?>


回答2:

Have you tried parse_url and parse_str ?



回答3:

Extract parameters and their values with-> &[\w]*=[\d]*