PHP function to remove variable from URL string
This function removes a variable name and variable value from an URL string, it will return the new string/url without the given variable, and will adjust the "?" or "&" character properly:
Example
remove_var_from_url("total_items","http://example.com?total_items=10&sort_by=price");
will return:
http://example.com?sort_by=price
The complete function is
<?php
if(!function_exists("remove_var_from_url")){
function remove_var_from_url($variable_name,$url_string){
if(strpos($url_string,"?")!==false){
$start_pos = strpos($url_string,"?");
$url_vars_strings = substr($url_string,$start_pos+1);
$names_and_values = explode("&",$url_vars_strings);
$url_string = substr($url_string,0,$start_pos);
foreach($names_and_values as $value){
list($var_name,$var_value)=explode("=",$value);
if($var_name != $variable_name){
if(strpos($url_string,"?")===false){
$url_string.= "?";
} else {
$url_string.= "&";
}
$url_string.= $var_name."=".$var_value;
}
}
}
return $url_string;
}
}?>
The oposite function (add variable to url) is also available.
Download the files
Download the function PHP file (1KB)