charlie
charlie

Reputation: 481

PHP function to remove specified variables in a URL

I have created this function to remove specific variables from a string

if(!function_exists("remove_variable")) {
    function remove_variable($remove = array(), $url) {
        if($url == '') {
            $url = $_SERVER["REQUEST_URI"];
        }

        foreach($remove as $r) {
            echo $r.'<br>';
            $url = preg_replace('/([?&])'.$r.'=[^&]+(&|$)/','$1', $url);
            echo $url.'<br><br>';
        }

        return $url;
    }
}

I am testing with:

<?php echo remove_variable(array("productsearch_name", "productsearch_type", "productsearch_supplier"), $_SERVER["REQUEST_URI"].uri_glue()); ?>

Which is returning:

productsearch_name
/companies/customers/pricelist?productsearch_name=&productsearch_type=Broadband%20&productsearch_supplier=&

productsearch_type
/companies/customers/pricelist?productsearch_name=&productsearch_supplier=&

productsearch_supplier
/companies/customers/pricelist?productsearch_name=&productsearch_supplier=&

/companies/customers/pricelist?productsearch_name=&productsearch_supplier=&

So it is not removing the variables as expected

Upvotes: 0

Views: 42

Answers (1)

Rahul
Rahul

Reputation: 18557

You can achieve this way,

$str = "http://google.com/companies/customers/pricelist?productsearch_name=asd&productsearch_type=Broadband%20&productsearch_supplier=test";
parse_str(parse_url($str)['query'],$output);
print_r($output);

parse_str — Parses the string into variables.
parse_url — Parse a URL and return its components

I hope this will solve your problem.

Upvotes: 1

Related Questions