Extract URL parameters with regex - repeating a capture group

Zach picture Zach · Oct 14, 2011 · Viewed 7.8k times · Source

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.

Answer

Hielo picture Hielo · Oct 14, 2011
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);
?>