What is a Query String?
A query string is the part of the URL that contains the data that is going to passed to via HTTP (GET). The query String typically is denoted by ( ? ) symbol.
See link below with query string:
www.someaddress.com?token=12&others=20&key=22
Removing QS:
Most of the time while working with URLs in PHP is spent extracting values from the query string. But what if you want to delete a key from the URL? In this post we are going to see how it can be accomplished.
Example 1:
Using $_GET array:
function remove_url_key($key){
// Set query url query string
$base_uri = $_SERVER['QUERY_STRING'];
$_new_uri = array();
// Verify if the key is set
if(!isset($_GET[$key]))
{
$q_string = $base_uri;
}
else
{
// Look for all values stored in $_GET array
foreach($_GET as $uri=>$val)
{
// If array values EQ to $key
if ($uri != $key)
{
// Assign values to new array
$_new_uri[$uri] = $val;
}
}
}
//build array to query string
$q_string = http_build_query($_new_uri);
// Return final url
return $q_string;
}
Example 2
Using parse_str()
function remove_url_key($key){
$base_uri = $_SERVER['QUERY_STRING'];
$q_string = "";
// Verify if the key is set
if(!isset($_GET[$key]))
{
$q_string = $base_uri;
}
else
{
// Parse $base_uri into $new_qs array
parse_str($base_uri, $new_qs);
// Delete $key with value EQ token
unset($new_qs[$key]);
//Build new query String
$q_string = http_build_query($new_qs);
}
// Return final url
return $q_string;
}
Helpful links:
parse_str - http://php.net/manual/en/function.parse-str.php
http_build_query - http://php.net/manual/en/function.http-build-query.php
$_SERVER- http://php.net/manual/en/reserved.variables.server.php

Recent Comments