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?
Asked
Active
Viewed 3.1k times
25
-
4possible 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
-
1you 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 Answers
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
-
It seems like parse_url throws a PHP error when using certain URLs, check out this comment on php.net: http://www.php.net/manual/en/function.parse-url.php#96433 – soren.qvist Jan 24 '11 at 16:22
-
1Yes, it seems it doesn't work on URLs without a `host` component. This will work with valid HTTP-like URLs. – Arnaud Le Blanc Jan 24 '11 at 16:29
-
-
it don't need the host in URL, just question mark (?) and parameters, $query = parse_url('?test=123&random=abc', PHP_URL_QUERY); – Hugo Ferreira Aug 07 '17 at 18:23
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
-
just out of curiosity, but how come your system doesn't support a native PHP function? – vallentin Jul 09 '15 at 18:35
-
@Vallentin - `parse_str()` was introduced in PHP 4... maybe (but it is much improbabile) he had a earlier version of PHP – Cliff Burton Jun 01 '16 at 10:14
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