Luqman Marzuki

Luqman Marzuki writes about anything

PHP to Remove Certain URL Parameter

PHP to Remove Certain URL Parameter

I recently build a small PHP script function to remove certain parameter from URL of the current page opened. If the parameter of a URL contains several variables like this: '?var1=val1&var2=val2&var3=val3', this script can remove var2 out from that query.

This URL parameter removing script is inserted into a function so it can be called several of times. By default, it will read the current URL parameter of the current opened page (The page where it is being called). The returned value from is a string containing the new URL parameter. Please be reminded that it doesn't include the base address.

Here is the code:

function rm_url_param($param_rm, $query='')
    empty($query)? $query=$_SERVER['QUERY_STRING'] : '';
    parse_str($query, $params);
    $newquery = '';
    foreach($params as $k => $v)
        { $newquery .= '&'.$k.'='.$v; }
    return substr($newquery,1);

Example Usage #1: remove var1 variable from current page's URL

$new_url_parameter = rm_url_param('var1');

With the above script, it will cut var1 from the URL and assign the new parameter string to new_url_parameter variable.


Example Usage #2: remove var1 variable from a given URL string

$url = '';
$parsedUrl = parse_url($url);
$new_url_parameter = rm_url_param('var1',parsedUrl['query']); 

With a full URL like that, we need to take only the parameters after the '?' sign from the link by using PHP function parse_url().


Example Usage #3: remove more than one variable (var1 and var2)  from current page's URL

$new_url_parameter = rm_url_param('var1',rm_url_param('var2'));

To remove more than one variable from a URL, simply iterate or loop the function on its second parameter.


Feel free to use if you found this is helping!