php; remove single variable value pair from querystring

前端 未结 4 2055
醉酒成梦
醉酒成梦 2021-01-17 23:38

I have a page that lists out items according to numerous parameters ie variables with values.

listitems.php?color=green&size=small&cat=pants&pa         


        
4条回答
  •  广开言路
    2021-01-18 00:08

    Here's my shot:

    /**
    *   Receives a URL string and a query string to remove. Returns URL without the query string
    */
    function remove_url_query($url, $key) {
        $url = preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url);
        $url = rtrim($url, '?');
        $url = rtrim($url, '&');
        return $url;
    }
    

    Returns:

    remove_url_query('http://example.com?a', 'a') => http://example.com
    remove_url_query('http://example.com?a=1', 'a') => http:/example.com
    remove_url_query('http://example.com?a=1&b=2', 'a') => http://example.com?b=2
    

    Kudos to David Walsh.

提交回复
热议问题