WordPress Code Snippets

A fresh mix of code snippets and tutorials

PHP Add and Remove Query String Variables

236

Two quick functions, one for adding a query string variable and another to remove a query string variable. Either of these functions can be used in any PHP script to modify query-string parameters.

Add Query String Variable

Here is a function that will add the specified query-string variable (key and value) to the specified URL:

function shapeSpace_add_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);
	}
}

This function accepts three variables:

  • $url – URL to which the query-string variable should be added
  • $key – query-string variable key
  • $value – query-string variable value

So for example, if you have the following URL:

http://example.com/whatever/?hello=world

..and you would like to add a query-string variable such as goodbye=nightclub, we can use the previous function like so:

$url = 'http://example.com/whatever/?hello=world';
shapeSpace_add_var($url, 'goodbye', 'nightclub');

The resulting URL will look like this:

http://example.com/whatever/?hello=world&goodbye=nightclub

Note that if the specified $key exists in the $url, it will be replaced.

Remove Query String Variable

Here is a similar function that removes the specified variable from the specified URL:

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

This function accepts only two variables, one for the URL and another for the variable key. For example, let’s say we want to remove hello=world from the previous URL. We can do this:

$url = 'http://example.com/whatever/?hello=world&goodbye=nightclub';
shapeSpace_remove_var($url, 'hello');

..and the result will look like this:

http://example.com/whatever/?goodbye=nightclub

Source: addedbytes.com


Show Support

Like our new Facebook Page to show support!