PHP: Remove Query String Parameter by Name

October 22, 2008

There are many times when I have come across situations where I need to remove a parameter from the query string of a URI. Usually these are involved in sorting data from a database, and I want to put a sort_by or some such in the URI as a GET. When the page loads I check for sort_by and if it exists I attempt to sort by it. The problem comes in when I have the link clicked on again. Usually this creates something like &sort_by=col1&sort_by=col2. Now obviously it will sort by the second, which is the one the user wants to sort by, but it looks tacky when they user sees multiple sort_bys in the query string. So I wanted to remove them. I did not know of, or find, a simple way to do this, so I created my own function using regular expressions(regex or regexp).

/**

* Will remove the passed in string from the url query string
* NOTE: This changes a global! If you do not desire this
*  sort of functionality change the last line to a return rather
*  than an assignment.
*
* @param string $needle - String to look for and remove
*/
function remove_from_query_string($content, $needle) {
    $query_string = $_SERVER['QUERY_STRING']; // Work on a seperate copy and preserve the original for now
   $query_string = preg_replace("/\&$needle=[a-zA-Z0-9].*?(\&|$)/", '&',   $query_string);
   $query_string = preg_replace("/(&)+/","&",$query_string); // Supposed to pull out all repeating &s, however it allows 2 in a row(&&). Good enough for now
   $_SERVER['QUERY_STRING'] = $query_string;
}

For an example of usage let’s assume we want to order our ascending or descending list with a get variable called ‘direction

$direction = 'asc';
if($_GET['direction'] == 'asc') {
    $direction = 'desc'; // Do the opposite
}
remvove_from_query_string('direction'); // Remove any existing &direction=...