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

时间:2013-10-04 12:42:21

标签: php

使用$_SERVER['REQUEST_URI'],我得到的网址可能是:

index.php 

index.php?id=x&etc..

我想做两件事:

  1. 查找index.php名称与正则表达式之后是否存在?something

  2. 如果网址中有特定的var( id = x )并从网址中删除它。

  3. 例如:

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

    我该怎么做?

2 个答案:

答案 0 :(得分:2)

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

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

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

由于您还希望在从网址的查询部分删除特定元素后重新创建网址,因此您可以使用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

Demo!

答案 1 :(得分:1)

如果必须是正则表达式:

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

echo $url;

输出

  ?

的index.php一个= 11&安培;

有一个尾随&,但上面删除了所有id = xxxxxxxx