How to remove a specific key from a query string using PHP

Sometimes you come across a situation where you need to remove a specific key from the query string.

I have come across a regular expression pattern on the internet which allows you to pass the complete query string as well as the key to remove from that string. The regular expression then returns the query string excluding that key and you can use it in your code.

Here is the function which accepts two parameters i.e. the complete query string and the key to be removed.

function remove_var($url, $key) { 
    $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); 
    $url = substr($url, 0, -1); 
    return $url; 
}

Now you can pass the requisite arguments to the function as follows

$strNewQS = remove_var($_SERVER['QUERY_STRING'], 'key to remove');

You can download sample script from GitHub

Hope the above helped.

Please follow and like us:
error