WP-Mix

A fresh mix of code snippets and tutorials

PHP Add and Remove Query Strings

Found a couple of useful PHP code snippets for adding and removing query strings from URLs. This is useful when implementing paged and search functionality, among other things. These functions work great and are a real time saver — copy, paste, test, and done.

Add query-string variable

This PHP function adds a query-string variable to the specified $url. The appended query-string variable will include the specified $key and $value. If $key already exists in the $url, it will be replaced with the new $value.

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

No modifications need made to this function. Simply add to your PHP script and call as needed, for example:

$url = add_querystring_var($url, $key, $value);

Remove query-string variable

Here is a similar function that will remove the specified query-string $key from the $url.

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

As before, no modifications need made to this function. Simply add to your PHP script and call as needed, for example:

$url = remove_querystring_var($url, $key);

Thanks to addedbytes.com for the code!

★ Pro Tip:

USP ProSAC Pro