如何获取当前的URL和修改参数PHP

问题描述 投票:1回答:1

我有一个这样的URL。

muliba/?i=page.alama&pro=as

我创建了一个这样的链接

<a href="<?php echo http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]."&pro=as";?>">AS</a>
<a href="<?php echo http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]."&pro=en";?>">EN</a>

如果我打开这个链接,参数被添加到已经定义的参数旁边,就像这样。

muliba/?i=page.alama&pro=as&pro=en

我怎样才能得到这样的结果?

muliba/?i=page.alama&pro=as
muliba/?i=page.alama&pro=en

谅谅

php url request-uri
1个回答
1
投票

根据 Scuzzy 回答和 jlcolon13 关于修改 Scuzzy 答以 Question 我把两个答案合并,让你更简单。只需复制下面的代码并粘贴到你的文件中!

function merge_querystring($url = null,$query = null,$recursive = false){
  // $url = 'https://www.google.com?q=apple&type=keyword';
  // $query = '?q=banana';
  // if there's a URL missing or no query string, return
  if($url == null)
    return false;
  if($query == null)
    return $url;
  // split the url into it's components
  $url_components = parse_url($url);
  // if we have the query string but no query on the original url
  // just return the URL + query string
  if(empty($url_components['query']))
    return $url.'?'.ltrim($query,'?');
  // turn the url's query string into an array
  parse_str($url_components['query'],$original_query_string);
  // turn the query string into an array
  parse_str(parse_url($query,PHP_URL_QUERY),$merged_query_string);
  // merge the query string
  if ($recursive == true) {
    $merged_result = array_filter(array_merge_recursive($original_query_string, $merged_query_string));
} else {
    $merged_result = array_filter(array_merge($original_query_string, $merged_query_string));
}

// Find the original query string in the URL and replace it with the new one
$new_url = str_replace($url_components['query'], http_build_query($merged_result), $url);

// If the last query string removed then remove ? from url 
if(substr($new_url, -1) == '?') {
   return rtrim($new_url,'?');
}
return $new_url;
}

使用方法

<a href="<?=merge_querystring($url,'?pro=en');?>">EN</a>
<a href="<?=merge_querystring($url,'?pro=as');?>">AS</a>

特别感谢 Scuzzy & jlcolon13

© www.soinside.com 2019 - 2024. All rights reserved.