Manipulate a url string by adding GET parameters

前端 未结 15 2109
旧巷少年郎
旧巷少年郎 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:20

    Use strpos to detect a ?. Since ? can only appear in the URL at the beginning of a query string, you know if its there get params already exist and you need to add params using &

    function addGetParamToUrl(&$url, $varName, $value)
    {
        // is there already an ?
        if (strpos($url, "?"))
        {
            $url .= "&" . $varName . "=" . $value; 
        }
        else
        {
            $url .= "?" . $varName . "=" . $value;
        }
    }
    

提交回复
热议问题