For example I have this URL address:

https://www.example.com?id=safety&order=1&price=0..995&property[172]=Canasafe

I can get query with this:

$_SERVER['QUERY_STRING']

which would output the following

id=safety&order=1&price=0..995&property[172]=Canasafe

Is it possible I get a query with only for example price and property? I want this:

?price=0..995&property[172]=Canasafe

3 Answers

2
Qirel On Best Solutions

Create an array with the indexes that you're looking for. Use a combination of parse_str() and parse_url() to get all the elements from your URL, and loop those - select those where they intersect with the $fetch_elements array. Then all you need is http_build_query() on that array!

$result = [];
$fetch_elements = ['property', 'price'];
$_SERVER['QUERY_STRING'] = 'https://www.example.com?id=safety&order=1&price=0..995&property[172]=Canasafe';

parse_str(parse_url($_SERVER['QUERY_STRING'], PHP_URL_QUERY), $elements);

foreach ($elements as $k=>$e) {
    if (in_array($k, $fetch_elements)) {
         $result[$k] = $e;
    }
}

echo urldecode(http_build_query($result));
1
Mohammad On

You can use regex to get target parts of url in preg_match_all()

preg_match_all("/price=[^&]+|property\[172\]=[^&]+/", $query, $m);
echo implode("&", $m[0]);

Check result in demo

0
pr1nc3 On

Yes you can simple use $_REQUEST

So to access price you can just use:

echo $_REQUEST['price'];

Example url

http://localhost/test.php?id=safety&order=1&price=0..995&property[172]=Canasafe

Output

0..995