php; remove single variable value pair from querystring

前端 未结 4 2052
醉酒成梦
醉酒成梦 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:00

    Another solution, to avoid & problems too!!!

    remove_query('http://example.com/?a=valueWith**&**inside&b=value');
    

    Code:

    function remove_query($url, $which_argument=false){ 
        return preg_replace('/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);  
    }
    
    0 讨论(0)
  • 2021-01-18 00:03

    It wouldn't work if edit=1 is the first variable:

    listitems.php?edit=1&color=green&...
    

    You can use the $_GET variable to create the query string yourself. Something like:

    $qs = '';
    foreach ($_GET as $key => $value){
        if ($key  == 'pagenum'){
            // Replace page number
            $qs .= $key  . '=' . $new_page_num . '&';
        }elseif ($key  != 'edit'){
            // Keep all key/values, except 'edit'
            $qs .= $key  . '=' . urlencode($value) . '&';
        }
    }
    
    0 讨论(0)
  • 2021-01-18 00:04

    I'd use http_build_query, which nicely accepts an array of parameters and formats it correctly. You'd be able to unset the edit parameter from $_GET and push the rest of it into this function.

    Note that your code has a missing call to htmlspecialchars(). A URL can contain characters that are active in HTML. So when outputting it into a link: Escape!

    Some example:

    unset($_GET['edit']); // delete edit parameter;
    $_GET['pagenum'] = 5; // change page number
    $qs = http_build_query($_GET);
    
    ... output link here.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题