How do I get the value of a query string from a URL value stored in a variable?

$ url = ' http://www.domain.com/file.php?dir=r&hl=100,200&ord=3&key=a+b+c ';

If it was the URL, I could get the value of hl, say, $_GET['hl']. but how to get the same from the string $ url.

Thank.

+5
source share
2 answers

Here are the steps:

$url = 'http://www.domain.com/file.php?dir=r&hl=100,200&ord=3&key=a+b+c';
print "<pre>";

print $url;

$url_parsed = parse_url($url);
print_r($url_parsed);

parse_str($url_parsed['query'], $url_parts);
print_r($url_parts);

print "</pre>";

Produces this conclusion:

http://www.domain.com/file.php?dir=r&hl=100,200&ord=3&key=a+b+cArray
(
    [scheme] => http
    [host] => www.domain.com
    [path] => /file.php
    [query] => dir=r&hl=100,200&ord=3&key=a+b+c
)
Array
(
    [dir] => r
    [hl] => 100,200
    [ord] => 3
    [key] => a b c
)

See parse_url()andparse_str()

So, to get the required value : h1

$url = 'http://www.domain.com/file.php?dir=r&hl=100,200&ord=3&key=a+b+c';
$url_parsed = parse_url($url);
parse_str($url_parsed['query'], $url_parts);
print $url_parts['h1'];
+6
source

With parse_url and parse_str .

$qs = parse_url($url, PHP_URL_QUERY);
parse_str($qs, $values);

This gives for $values:

array (4) {
  ["dir"] =>
  string(1) "r"
  ["hl"]=>
  string(7) "100,200"
  ["ord"]=>
  string(1) "3"
  ["key"]=>
  string(5) "a b c"
}
+4

All Articles