First function is a helper function to remove the query string and rebuild it with http_build_query
.
/** * Shellcreeper Helper function to remove query string * * @param $varname string variable to remove * @param $query_string string query data * @link https://shellcreeper.com/?p=440 */ function sc_remove_query_string( $varname, $query_string ) { /* make sure it's an array */ $query_array = array(); /* Parses the string into variables */ parse_str( $query_string, $query_array ); /* Remove */ unset($query_array[$varname]); /* Rebuild the query */ $query_string = http_build_query($query_array); /* return */ return $query_string; }
Now this is the function to remove a query variable, from url string:
/** * Shellcreeper Remove query variable from url * * @param $param string url parameter to remove * @param $page_url string url source * @uses sc_remove_query_string() * @link https://shellcreeper.com/?p=440 */ function sc_remove_url_var( $param, $page_url ){ /* parse url data */ $url_data = array(); $url_data = parse_url( $page_url ); /* vars */ $query_string = ''; $page_url_new = ''; $url_data_host = ''; $url_data_path = ''; /* remove query string from url */ if (isset($url_data['query'])) $query_string = sc_remove_query_string( $param, $url_data['query'] ); /* new url */ if ( isset( $url_data['host'] ) ) $url_data_host = $url_data['host']; if ( isset($url_data['path'])) $url_data_path = $url_data['path']; $page_url_new = $url_data_host.$url_data_path; /* if there's no string use "?" */ if ( !empty( $query_string ) ) $page_url_new .= '?' . $query_string; /* add things after the hashmark # */ if (isset($url_data['fragment'])) $page_url_new .= $url_data['fragment']; /* close sesame */ return $page_url_new; }
usage example: remove variable var1
from current url:
$current_uri = $_SERVER['REQUEST_URI']; $clean_uri = sc_remove_url_var( 'var1', $current_uri ); print $clean_uri;
so:
http://domain.com/?var1=value1&var2=value2&var3=value3
will be:
http://domain.com/?var2=value2&var3=value3