better way to replace query string value in a given url

前端 未结 8 2025
南方客
南方客 2020-12-11 16:32

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\";

8条回答
  •  清歌不尽
    2020-12-11 17:21

    How about something like 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);
    }
    

    usage...

    Page 1
    Page 2
    

提交回复
热议问题