25

Users can input URLs using a HTML form on my website, so they might enter something like this: http://www.example.com?test=123&random=abc, it can be anything. I need to extract the value of a certain query parameter, in this case 'test' (the value 123). Is there a way to do this?

soren.qvist
  • 7,376
  • 14
  • 62
  • 91
  • 4
    possible duplicate of [Regular expression to parse query string](http://stackoverflow.com/questions/4499538/regular-expression-to-parse-query-string) – Gordon Jan 24 '11 at 16:23
  • Indeed, a duplicate, however the parse_url solution leads to a new problem, look at my comment to user576875 below. – soren.qvist Jan 24 '11 at 16:28
  • 1
    you could extract the string starting from `?` with `strstr` or `explode` something and then pass that to `parse_str` – Gordon Jan 24 '11 at 16:40
  • It looks like I can use strstr, thanks Gordon – soren.qvist Jan 24 '11 at 16:58

3 Answers3

65

You can use parse_url and parse_str like this:

$query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
parse_str($query, $params);
$test = $params['test'];

parse_url allows to split an URL in different parts (scheme, host, path, query, etc); here we use it to get only the query (test=123&random=abc). Then we can parse the query with parse_str.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
2

I needed to check an url that was relative for our system so I couldn't use parse_str. For anyone who needs it:

$urlParts = null;
preg_match_all("~[\?&]([^&]+)=([^&]+)~", $url, $urlParts);
Rob
  • 2,466
  • 3
  • 22
  • 40
1

the hostname is optional but is required at least the question mark at the begin of parameter string:

$inputString = '?test=123&random=abc&usersList[]=1&usersList[]=2' ;

parse_str ( parse_url ( $inputString , PHP_URL_QUERY ) , $params );

print_r ( $params );
Hugo Ferreira
  • 184
  • 13