Tuesday 14 August 2018

PHP Function: Remove a Query String Key=>Value

I was recently coding a website which relied heavily on query string variables. It was absolutely imperative that I keep the query string clean and not duplicate keys. I needed to find a PHP function that would allow me to remove keys (and their values) easily and reliably. Enter a PHP function I found at Added Bytes:


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

/* usage */
//pretending this page is
All I needed to do was provide the URL (in my case I wanted the current page's URI) and the key to remove -- so simple!

All credit goes to Added Bytes for their awesome work. It saved me a lot of time...hopefully it does for you too!

0 comments:

Post a Comment