Remove specific parameter from URL while preserving other parameters

11,491

Solution 1

$link = preg_replace('~(\?|&)counter=[^&]*~','$1',$link);

Solution 2

Relying on regular expressions can screw things up sometimes..

You should use, the parse_url() function which breaks up the entire URL and presents it to you as an associative array.

Once you have that array, you can edit it as you wish and remove parameters.

Once, completed, use the http_build_url() function to rebuild the URL with the changes made.

Check the docs here..

Parse_Url Http_build_query()

EDIT

Whoops, forgot to mention. After you get the parameter string, youll obviously need to separate the parameters as individual ones. For this you can supply the string as input to the parse_str() function.

You can even use explode() with & as the delimeter to get this done.

Solution 3

A code example how I would grab a requested URL and remove a parameter called "name", then reload the page:

$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //complete url
$parts = parse_url($url);
parse_str($parts['query'], $query); //grab the query part
unset($query['name']); //remove a parameter from query
$dest_query = http_build_query($query); //rebuild new query
$dest_url=(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http").'://'.$parts['path'].'?'.$dest_query; //add query to host
header("Location: ".$dest_url); //reload page

Solution 4

I would recommend using a combination of parse_url() and http_build_query().

Solution 5

Handle it correctly! !

remove_query('http://example.com/?a=valueWith**&**inside&b=value');

Code:

function remove_query($url, $which_argument=false){ 
    return preg_replace( '/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);  
}
Share:
11,491
Alaa Gamal
Author by

Alaa Gamal

Updated on June 18, 2022

Comments

  • Alaa Gamal
    Alaa Gamal about 2 years

    I want remove a parameter from a URL:

    $linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
    $linkExample2='https://stackoverflow.com/?counter=4&star=5';
    

    I am trying to get this result:

    I am trying to do it using preg_replace, but I've no idea how it can be done.