Search code examples
phpregexurlget

Obtain the GET parameters of URL by RegEx in PHP


I am on the way of learning regular expressions and I try to find an opportunity to grab the GET parameters from the given URL. For example find the words between ? and = and between & and =

I have tried something like this

$query = $_REQUEST["query"];
preg_match_all('/\B(\?|&).*=\B/', $query, $param_keys);

https://regex101.com/r/ZzB4pX/1

But seems it's not working correct. Additionally how can I get the last word which is going right after the last =?


Solution

  • You can get the query parameters with a regex like this:

    [\?|&](.*?)=([^&]*)
    

    Translation: Look for a pattern that starts with either ? or &, followed by the smallest amount of random characters (which we capture in a capturing group), followed by a = followed by the largest group of non-& characters you can find (also in a capturing group).