PHP Query String Manipulation

前端 未结 4 1821
我寻月下人不归
我寻月下人不归 2021-01-17 06:16

Any one have the ultimate PHP function(s) to add/remove parameters from a query string? It needs to handle all possible cases, Ive seen ones that handle some cases, but not

4条回答
  •  感动是毒
    2021-01-17 06:58

    This is the sketch for the function you can start with:

    function add_get_param($url, $param, $value)
    {
            $parts_url = parse_url($url);
    
            parse_str($parts_url['query'], $parts_query);
    
            $parts_query[$param] = $value;
    
            return $parts_url['scheme'] . '://' . $parts_url['host'] . '/' . $parts_url['path'] . '?' . http_build_query($parts_query);
    }
    
    var_dump(add_get_param('http://mysite.com?param1=1¶m2=2', 'param3', 3));
    

    UPD: since parse_str breaks the data (replaces dots with underscores) I don't think this sketch is useful.

提交回复
热议问题