3

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.

Zach
  • 9,591
  • 1
  • 38
  • 33

3 Answers3

10
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);
?>
Hielo
  • 371
  • 1
  • 3
5

Have you tried parse_url and parse_str ?

JRL
  • 76,767
  • 18
  • 98
  • 146
0

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

Romaine Carter
  • 637
  • 11
  • 23