如何获取和更改 URL 变量 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16036775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:25:42  来源:igfitidea点击:

How to get and change URL variable PHP

phphtmlhyperlink

提问by CaffeineShots

Hi could anyone help me with this I have a URL like

嗨,谁能帮我解决这个问题,我有一个类似的网址

parent/child/a=1&b=2$c=3

then I have a link that would add variable to that URL

然后我有一个链接,可以向该 URL 添加变量

<a href="<?php echo $_SERVER["REQUEST_URI"]."&d=test1";?>">LINK 1</a>
<a href="<?php echo $_SERVER["REQUEST_URI"]."&d=test2";?>">LINK 2</a>

every time I click my link the variable d to URL keep on reproducing like this

每次我单击我的链接时,变量 d 到 URL 都会像这样继续复制

parent/child/a=1&b=2&c=3&d=test2&d=test2&d=test2&d=test1&d=test1

I know that the $_SERVER["REQUEST_URI"] keep getting the current URL that is why I get that result. I have tried the some of properties of $_SERVER[""]. What I like is to change the d variable value, any idea how to do it. Any response is well appreciated.Thanks!

我知道 $_SERVER["REQUEST_URI"] 不断获取当前 URL,这就是我得到该结果的原因。我已经尝试了 $_SERVER[""] 的一些属性。我喜欢的是改变 d 变量值,不知道怎么做。任何回应都非常感谢。谢谢!

回答by Michael Eugene Yuen

$query = $_GET;
// replace parameter(s)
$query['d'] = 'new_value';
// rebuild url
$query_result = http_build_query($query);
// new link
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?<?php echo $query_result; ?>">Link</a>

回答by Vinoth Babu

Try with the below expression, It Should Work

尝试使用以下表达式,它应该可以工作

preg_replace("#&d=.*&#", '&d=newvalue&', $_SERVER['REQUEST_URI'])

回答by ihorsl

modify_url_query($url, array('limit' => 50));

My function for modifying query in url

我在 url 中修改查询的功能

function modify_url_query($url, $mod){

$purl = parse_url($url);

$params = array();

if (($query_str=$purl['query']))
{
    parse_str($query_str, $params);

    foreach($params as $name => $value)
    {
        if (isset($mod[$name]))
        {
            $params[$name] = $mod[$name];
            unset($mod[$name]);
        }
    }
}        

$params = array_merge($params, $mod);

$ret = "";

if ($purl['scheme'])
{
    $ret = $purl['scheme'] . "://";
}    

if ($purl['host'])
{
    $ret .= $purl['host'];
}    

if ($purl['path'])
{
    $ret .= $purl['path'];
}    

if ($params)
{
    $ret .= '?' . http_build_query($params);
}    


if ($purl['fragment'])
{
    $ret .= "#" . $purl['fragment'];
}        

return $ret;

}

回答by Venkat Kotra

To remove repeated addition of query parameter do the below

要删除重复添加查询参数,请执行以下操作

// parse the url
$pathInfo = parse_url($_SERVER['REQUEST_URI']);
$queryString = $pathInfo['query'];
// convert the query parameters to an array
parse_str($queryString, $queryArray);
// add the new query parameter into the array
$queryArray['d'] = 1;
// build the new query string
$newQueryStr = http_build_query($queryArray);

// construct new url
?>
<a href="<?php echo $pathInfo['host'].'?'.$newQueryStr;?>">LINK 1</a>

回答by Vikas Chauhan

function replaceUrlParameters($url = '', $newParams = array()){
    if($url){
        $urlArray = parse_url($url);
        $queryString = $urlArray['query'];
        parse_str($queryString, $queryParams);
        $queryParams = array_merge($queryParams, $newParams);
        $urlArray['query'] = http_build_query($queryParams);

        if(!empty($urlArray)){
            $url = $urlArray['scheme'].'://'.$urlArray['host'].$urlArray['path'].'?'.$urlArray['query'];
        }
    }
    return $url;
}
// $newParams = array of new parameters or old parameters with new value
$replacedUrl = replaceUrlParameters($url, $newParams);

Suppose you have url like :- <?php echo $_SERVER["REQUEST_URI"]."&a=test1&b=test2";?>and you want to replace parameter b's value to test3 then just pass this url and an array with the same index with new value. for ex- <?$url = $_SERVER["REQUEST_URI"]."&a=test1&b=test2";?> <? $newParams = ['b' => 'test3']?>then you will get - <? $_SERVER["REQUEST_URI"]."&a=test1&b=test3";?>

假设您有类似 :- 的 url,<?php echo $_SERVER["REQUEST_URI"]."&a=test1&b=test2";?>并且您想将参数 b 的值替换为 test3,然后只需传递此 url 和一个具有相同索引的数组和新值。对于前 -<?$url = $_SERVER["REQUEST_URI"]."&a=test1&b=test2";?> <? $newParams = ['b' => 'test3']?>那么你会得到 -<? $_SERVER["REQUEST_URI"]."&a=test1&b=test3";?>

回答by Pasi Matalam?ki

Couldn't still find fitting solution myself, so created one..

自己仍然无法找到合适的解决方案,所以创建了一个..

static function changeParameters($url, $parameters)
{
    $urlParts = parse_url($url);


    $url = "";

    if (isset($urlParts['scheme'])) {
        $url .= $urlParts['scheme'] . "://";
    }

    if (isset($urlParts['host'])) {
        $url .= $urlParts['host'];
    }

    if (isset($urlParts['path'])) {
        $url .= $urlParts['path'];
    }

    $query = isset($urlParts['query']) ? $urlParts['query'] : "";

    $urlParameters = explode("&", $query);

    $urlParameterValuesByKey = new stdClass();

    foreach ($urlParameters as $urlParameter) {
        $equalsIndex = strrpos($urlParameter, "=");

        if ($equalsIndex) {
            $urlParameterValuesByKey->{substr($urlParameter, 0, $equalsIndex)} = substr($urlParameter, $equalsIndex + 1);
        } else {
            $urlParameterValuesByKey->{$urlParameter} = null;
        }
    }

    foreach ($parameters as $key => $value) {
        if(!is_string($value)) {
            unset($urlParameterValuesByKey->{$key});
        } else {
            $urlParameterValuesByKey->{$key} = $value;
        }
    }

    $query = "";

    foreach ($urlParameterValuesByKey as $key => $value) {
        if (strlen($query) === 0) {
            $query .= "?";
        }

        if (strlen($query) > 1) {
            $query .= "&";
        }
        if (is_string($value)) {
            $query .= $key . "=" . $value;
        } else {
            $query .= $key;
        }
    }


    $url .= $query;

    return $url;
}

Uses stdClass instead of associative array, because associative arrays does some funky stuff for the keys before setting them, as described here.

使用 stdClass 而不是关联数组,因为关联数组在设置键之前为键做了一些时髦的事情,如here所述。

回答by Code L?ver

Here you have not take care of the double quotation. Replace that with the following code and then check.

这里你没有处理双引号。将其替换为以下代码,然后检查。

<a href="<?php echo 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].'&d=test1';?>">LINK 1</a>

And also check in firebug that what URL is in href each time.

并且还检查萤火虫每次在href 中的URL 是什么。