Manipulate a url string by adding GET parameters

前端 未结 15 2100
旧巷少年郎
旧巷少年郎 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-29 01:20

    Try this function to add URL parameters.

    Then you can disable the link when parameter is set so there is no url parameter duplicate.

    <?php
      function addQueryString($a)
                    {
                 if (empty($_SERVER['QUERY_STRING']))
                   return '?' . $a;
                 else if (!empty($_SERVER['QUERY_STRING']))
                  return '?' . $_SERVER['QUERY_STRING'] . '&' . $a;
                    }
    ?>
    
     <a href="<?php echo addQueryString('lang=en'); ?>">test</a>
     <a href="<?php echo addQueryString('category=5'); ?>">sat</a>
    
    0 讨论(0)
  • 2020-11-29 01:20

    In case you are using WordPress you can simply use

        add_query_args(['sort' => 'asc'], 'http:/example.com/?search=news')
    

    Docs https://developer.wordpress.org/reference/functions/add_query_arg/

    0 讨论(0)
提交回复
热议问题