better way to replace query string value in a given url

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

提交回复
热议问题