从 URI 字符串中删除特定变量


Remove specific variable from URI string

使用 $_SERVER['REQUEST_URI'] ,我得到一个 URL 可能是:

index.php 

index.php?id=x&etc..

我想做两件事:

  1. 查找index.php名称后是否有带有正则表达式的内容。

  2. 如果 url 中有特定的变量 (id=x),并将其从 url 中删除。

例如:

index.php?id=x       => index.php 
index.php?a=11&id=x  => index.php?a=11

我该怎么做?

要检查 index.php 后是否有?something,可以使用内置函数 parse_url() ,如下所示:

if (parse_url($url, PHP_URL_QUERY)) {
    // ?something exists
}

要删除id,您可以使用 parse_str() ,获取查询参数,将它们存储在数组中,然后取消设置特定的id

而且,由于您还希望在从URL的查询部分删除特定元素后重新创建URL,因此您可以使用http_build_query() .

这是一个函数:

function removeQueryString($url, $toBeRemoved, $match) 
{
    // check if url has query part
    if (parse_url($url, PHP_URL_QUERY)) {
        // parse_url and store the values
        $parts = parse_url($url);
        $scriptname = $parts['path'];
        $query_part = $parts['query'];
        // parse the query parameters from the url and store it in $arr
        $query = parse_str($query_part, $arr);
        // if id == x, unset it
        if (isset($arr[$toBeRemoved]) && $arr[$toBeRemoved] == $match) {
            unset($arr[$toBeRemoved]);
            // if there less than 1 query parameter, don't add '?'
            if (count($arr) < 1) {
                $query = $scriptname . http_build_query($arr);
            } else {
                $query = $scriptname . '?' . http_build_query($arr);  
            }
        } else {
            // no matches found, so return the url
            return $url;
        }
        return $query;
    } else {
        return $url;
    }
}

测试用例:

echo removeQueryString('index.php', 'id', 'x');
echo removeQueryString('index.php?a=11&id=x', 'id', 'x');
echo removeQueryString('index.php?a=11&id=x&qid=51', 'id', 'x');
echo removeQueryString('index.php?a=11&foo=bar&id=x', 'id', 'x');

输出:

index.php
index.php?a=11
index.php?a=11&qid=51
index.php?a=11&foo=bar

演示!

如果它必须是正则表达式:

$url='index.php?a=11&id=1234';
$pattern = '#'id='d+#';
$url = preg_replace($pattern, '', $url);
echo $url;

输出

index.php?a=11&

有一个尾随&,但上面删除了任何 id=xxxxxxxxx