better way to replace query string value in a given url

前端 未结 8 1997
南方客
南方客 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:11

    improve Scuzzy 2013 function last pieces for clean url query string.

    // merge the query string
    // array_filter removes empty query array
        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;
    
    0 讨论(0)
  • 2020-12-11 17:16

    Well, I had same problem, found this question, and, in the end, prefered my own method. Maybe it has flaws, then please tell me what are they. My solution is:

    $query=$_GET;
    $query['YOUR_NAME']=$YOUR_VAL;
    $url=$_SERVER['PHP_SELF']. '?' .  http_build_query($query);
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-11 17:16
    function replaceQueryParams($url, $params)
    {
        $query = parse_url($url, PHP_URL_QUERY);
        parse_str($query, $oldParams);
    
        if (empty($oldParams)) {
            return rtrim($url, '?') . '?' . http_build_query($params);
        }
    
        $params = array_merge($oldParams, $params);
    
        return preg_replace('#\?.*#', '?' . http_build_query($params), $url);
    }
    

    $url examples:

    • http://example.com
    • http://example.com/
    • http://example.com/page
    • http://example.com/page?
    • http://example.com/page?foo=bar
    • http://example.com/page?foo2=bar2
    • http://example.com/page?foo=bar&foo2=bar2

    $params example:

    [
       'foo' => 'not-bar',
    ]
    

    Note: it doesn't understand URLs with anchors (hashes) like http://example.com/page?foo=bar#section1

    0 讨论(0)
  • 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...

    <a href="<?=merge_querystring($url,'?page=1');?>">Page 1</a>
    <a href="<?=merge_querystring($url,'?page=2');?>">Page 2</a>
    
    0 讨论(0)
  • 2020-12-11 17:24

    If I'm reading this correctly, and I may not be. You know which GET you are replacing in a url string? This may be sloppy but...

    $url_pieces = explode( '?', $url );
    $var_string = $url_pieces[1].'&';
    $new_url = $url_pieces[0].preg_replace( '/varName\=value/', 'newVarName=newValue', $var_string );
    

    That's my take, Good luck.

    0 讨论(0)
  • 2020-12-11 17:24

    I don't know if this is what you're trying to accomplish but here it goes anyway:

    <?php
        function mergeMe($url, $assign) {
            list($var,$val) = explode("=",$assign);
            //there's no var defined
            if(!strpos($url,"?")) {
                $res = "$url?$assign";
            } else {
                list($base,$vars) = explode("?",$url);
                //if the vars dont include the one given
                if(!strpos($vars,$var)) {
                    $res = "$url&$assign";
                } else {
                    $res = preg_replace("/$var=[a-zA-Z0-9_]*(&|$)/",$assign."&",$url);
                    $res = preg_replace("/&$/","",$res); //remove possible & at the end
                }
            }
            //just to show the difference, should be "return $res;" instead
            return "$url <strong>($assign)</strong><br>$res<hr>";
        }
    
        //example
        $url1 = "http://example.com";
        $url2 = "http://example.com?sort=a";
        $url3 = "http://example.com?sort=a&page=0";
        $url4 = "http://example.com?sort=a&page=0&more=no";
    
        echo mergeMe($url1,"page=4");
        echo mergeMe($url2,"page=4");
        echo mergeMe($url3,"page=4");
        echo mergeMe($url4,"page=4");
    ?>
    
    0 讨论(0)
提交回复
热议问题