Extract URL parameters with regex - repeating a capture group

8.7k views Asked by At

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.

3

There are 3 answers

0
Hielo On BEST ANSWER
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);
?>
0
Romaine Carter On

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

0
JRL On

Have you tried parse_url and parse_str ?