php;从querystring中删除单个变量值对


php; remove single variable value pair from querystring

我有一个页面,列出了项目根据众多参数即变量值。

listitems.php?color=green&size=small&cat=pants&pagenum=1 etc.

为了允许编辑列表,我有一个参数edit=1,它被附加到上面的查询字符串中:

listitems.php?color=green&size=small&cat=pants&pagenum=1&edit=1

一切顺利。

当用户完成编辑时,我有一个退出编辑模式的链接。我希望这个链接指定整个querystring——不管它可能是什么,因为这取决于用户的选择——除了删除edit=1。

当我只有几个变量时,我只是在链接中手动列出它们,但现在有更多,我希望能够以编程方式删除edit=1。

我是否应该对edit=1进行某种搜索,然后将其替换为空?

$qs = str_replace("&edit=1, "", $_SERVER['QUERY_STRING']);
<a href='{$_SERVER['PHP_SELF']}?{$qs}'>return</a>;

或者什么是最干净,最没有错误的方法来做这件事。

注意:我有一个类似的情况,当从一页到另一页,我想拿出pagenum,并用不同的替换它。在那里,由于pagenum变化,我不能只搜索pagenum=1,而必须搜索pagenum =$pagenum,如果这有任何区别的话。

谢谢。

我将使用http_build_query,它可以很好地接受参数数组并正确格式化它。您可以从$_GET中取消edit参数的设置,并将其其余部分推入该函数。

请注意,您的代码有一个对htmlspecialchars()的缺失调用。URL可以包含在HTML中活动的字符。因此,当输出到链接中时:Escape!

一些例子:

unset($_GET['edit']); // delete edit parameter;
$_GET['pagenum'] = 5; // change page number
$qs = http_build_query($_GET);
... output link here.

这是我的镜头:

/**
*   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;
}

的回报:

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

向David Walsh致敬

另一个解决方案,也可以避免&amp;问题!!

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

function remove_query($url, $which_argument=false){ 
    return preg_replace('/'. ($which_argument ? '('&|)'.$which_argument.'('=(.*?)((?=&(?!amp';))|$)|(.*?)'b)' : '('?.*)').'/i' , '', $url);  
}

如果edit=1是第一个变量,则不起作用:

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

您可以使用$_GET变量自己创建查询字符串。比如:

$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) . '&';
    }
}