Manipulate a url string by adding GET parameters

前端 未结 15 2104
旧巷少年郎
旧巷少年郎 2020-11-29 00:50

I want to add GET parameters to URLs that may and may not contain GET parameters without repeating ? or &.

Example:

If I want t

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 01:10

    Basic method

    $query = parse_url($url, PHP_URL_QUERY);
    
    // Returns a string if the URL has parameters or NULL if not
    if ($query) {
        $url .= '&category=1';
    } else {
        $url .= '?category=1';
    }
    

    More advanced

    $url = 'http://example.com/search?keyword=test&category=1&tags[]=fun&tags[]=great';
    
    $url_parts = parse_url($url);
    // If URL doesn't have a query string.
    if (isset($url_parts['query'])) { // Avoid 'Undefined index: query'
        parse_str($url_parts['query'], $params);
    } else {
        $params = array();
    }
    
    $params['category'] = 2;     // Overwrite if exists
    $params['tags'][] = 'cool';  // Allows multiple values
    
    // Note that this will url_encode all values
    $url_parts['query'] = http_build_query($params);
    
    // If you have pecl_http
    echo http_build_url($url_parts);
    
    // If not
    echo $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];
    

    You should put this in a function at least, if not a class.

提交回复
热议问题