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?
3 Answers
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.
4 Comments
soren.qvist
It seems like parse_url throws a PHP error when using certain URLs, check out this comment on php.net: php.net/manual/en/function.parse-url.php#96433
Arnaud Le Blanc
Yes, it seems it doesn't work on URLs without a
host component. This will work with valid HTTP-like URLs.soren.qvist
So, is there any other way to do this?
Hugo Ferreira
it don't need the host in URL, just question mark (?) and parameters, $query = parse_url('?test=123&random=abc', PHP_URL_QUERY);
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);
2 Comments
vallentin
just out of curiosity, but how come your system doesn't support a native PHP function?
Cliff Burton
@Vallentin -
parse_str() was introduced in PHP 4... maybe (but it is much improbabile) he had a earlier version of PHP
?withstrstrorexplodesomething and then pass that toparse_str