Search code examples
phpreplaceuripreg-replacequery-string

Remove a specific key-value pair from the query string of a URI string


I have this input string:

http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&brand=Sony&toto=titi

I'd like to end up with this output string:

http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&kljklj=sdfsd

I want to delete &brand=Sony

I tried this :

preg_replace('/(^.*)(&brand=.*)(&.*)/', '$1$3', 'http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&brand=Sony&toto=titi');

but it doesn't work in a specific case : the case where the parameter "toto" in the URI doesn't exist

So if I do

preg_replace('/(^.*)(&brand=.*)(&.*)/', '$1$3', 'http://localhost/prixou/index.php?page=list&category=1&sub=1&subsub=0&brand=Sony'); 

It doesn't work; &brand=Sony still appears.

So how can I do?


Solution

  • Thank you everybody. So here is my final solution and it works fine :

    <?php
    $actual_link = 'index.php?'.$_SERVER['QUERY_STRING']; //complete link of my page
    $parsedURL= parse_url($actual_link);
    parse_str($parsedURL["query"],$tabParametersQuery);    
    $tabParametersQuery['brand']="";
    $newURL = "index.php?".http_build_query($tabParametersQuery);
    ?>