0

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

3
  • 2
    i would use parse_str not a regular expression Commented Dec 5, 2016 at 20:50
  • 1
    And then array_diff_key() with the array you want to remove. Commented Dec 5, 2016 at 21:01
  • @Dagon how would you use parse_str ? Commented Dec 5, 2016 at 22:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.