PHP函数用于删除URL中的指定变量

时间:2016-12-05 20:37:31

标签: php

我已创建此函数以从字符串

中删除特定变量
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;
    }
}

我正在测试:

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

返回:

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=&

所以它没有按预期删除变量

1 个答案:

答案 0 :(得分:1)

你可以这样做,

$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 - 将字符串解析为变量 parse_url - 解析URL并返回其组件

我希望这能解决你的问题。