在给定 url 中替换查询字符串值的更好方法 [英] better way to replace query string value in a given url

查看:47
本文介绍了在给定 url 中替换查询字符串值的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的..所以基本上,假设我们有一个链接:

Okay.. so basically, say we have a link:

$url = "http://www.site.com/index.php?sub=Mawson&state=QLD&cat=4&page=2&sort=z";

基本上,我需要创建一个函数,它替换 URL 中的每个东西,例如:

Basically, I need to create a function, which replaces each thing in the URL, for example:

<a href="<?=$url;?>?sort=a">Sort by A-Z</a>
<a href="<?=$url;?>?sort=z">Sort by Z-A</a>

或者,再举一个例子:

<a href="<?=$url;?>?cat=1">Category 1</a>
<a href="<?=$url;?>?cat=2">Category 2</a>

或者,另一个例子:

<a href="<?=$url;?>?page=1">1</a>
<a href="<?=$url;?>?page=2">2</a>
<a href="<?=$url;?>?page=3">3</a>
<a href="<?=$url;?>?page=4">4</a>

所以基本上,我们需要一个函数来替换 URL 中特定的 $_GET 以便我们不会得到重复,例如:?page=2&page=3

So basically, we need a function which will replace the specific $_GET from the URL so that we don't get a duplicate, such as: ?page=2&page=3

话虽如此,它需要聪明,所以它知道参数的开头是?还是&

Having said that, it needs to be smart, so it knows if the beginning of the parameter is a ? or an &

我们还需要它是智能的,以便我们可以拥有这样的 URL:

We also need it to be smart so that we can have the URL like so:

<a href="<?=$url;?>page=3">3</a> (without the ? - so it will detect automatically wether to use an `&` or a `?`

我不介意为某些 $_GET 参数为每​​个 preg_replace 制作不同的变量,但我正在寻找最好的方法来做到这一点.

I don't mind making different variables for each preg_replace for the certain $_GET parameters, but I am looking for the best way to do this.

谢谢.

推荐答案

这样的事情怎么样?

function merge_querystring($url = null,$query = null,$recursive = false)
{
  // $url = 'http://www.google.com.au?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_merge_recursive($original_query_string,$merged_query_string);
  else
    $merged_result = array_merge($original_query_string,$merged_query_string);
  // Find the original query string in the URL and replace it with the new one
  return str_replace($url_components['query'],http_build_query($merged_result),$url);
}

用法...

<a href="<?=merge_querystring($url,'?page=1');?>">Page 1</a>
<a href="<?=merge_querystring($url,'?page=2');?>">Page 2</a>

这篇关于在给定 url 中替换查询字符串值的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆