0

I found a bit of code for stripping a query string and adding a new value to it, but I want to be able to do this with an array of options. Could someone give me a hand in modifying this code to do that?

Current code:

function add_querystring_var($url, $key, $value) {
    $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
    $url = substr($url, 0, -1);    
    $value = $value ? "=".urlencode($value) : '';    
    if (strpos($url, '?') === false)
        return ($url . '?' . $key . $value);
    else
        return ($url . '&' . $key . $value);
}

And I want it to do a foreach for each key and value given and then rebuild the new url.

Example: add_querystring_var(curPageURL(), array("order","sort"), array("swn","DESC"))

So I want the following URL http://www.example.com/students when put through the example above would return http://www.example.com/students?order=swn&sort=DESC

Does anyone know how I can do this? I'm new to this area of PHP. :)

UPDATE: I forgot to mention sometimes the url may have other queries in it, so I want it to replace the ones that I enter into my array.

Example 1: http://www.example.com/students?page=2 would need to turn into http://www.example.com/students?page=2&order=swn&sort=DESC

Example 2: http://www.example.com/students?page=2&order=name&sort=ASC would need to turn into http://www.example.com/students?page=2&order=swn&sort=DESC

2
  • Why don't you just use the built-in http_build_query() function? Commented May 28, 2013 at 0:04
  • @Barmar I just found that before, but wasn't sure how to use it in this case? Any suggestions? Commented May 28, 2013 at 0:06

2 Answers 2

1
  function add_querystring_var($url, $additions) {
    $parsed = parse_url($url);
    if (isset($parsed['query'])) {
        parse_str($parsed['query'], $query);
    } else {
        $query = array();
    }
    $parsed['query'] = http_build_query(array_merge($query, $additions));
    return http_build_url($parsed);
  }

Use it this way:

$new_url = add_querystring_var($url, array('order' => 'swn', 'sort' => 'DESC'));

If you're getting errors saying that http_build_url is not defined, see

PHP http_build_url() and PECL Install

Sign up to request clarification or add additional context in comments.

13 Comments

Thanks but that didn't work? I just got an error. Should the function have add_querystring_var($url, &$additions) not add_querystring_var($url, $additions)? But then I get an error Fatal error: Cannot pass parameter 2 by reference in.
Why should the additions be a reference parameter? It's not modifying it. I've fixed a problem when the original URL doesn't have a query string.
I think I've missed something? I'm getting the error Fatal error: Call to undefined function http_build_url()
Yeah, I'm getting that too. I thought it was just because I didn't have an optional PECL package installed, so hoped it would work for you.
thanks but now that's just returning an error parse_url() expects parameter 1 to be string, array given from the result
|
0

You're kind of reinventing the wheel with that function... first off, you'd be better off using urlencode() on your key/value data rather than that regular expression (and I see that you're not encoding your value string at all)

As dpDesignz mentions in his comment - there is a built-in function available: http_build_query()

$querydata = array('foo' => array('bar', 'baz'),
          'baz'=>'boom',
          'cow'=>'milk',
          'php'=>'hypertext processor');

$querystring = http_build_query($data, '', '&');

Or, to use your example:

$querydata = array("order" => "swn", "sort" => "DESC");
$url = curPageURL();
$concat = "?";
if (strpos($url, "?") !== false)) {
    $concat = "&"
}
$url .= $concat . http_build_query($data, '', '&');

6 Comments

thanks for this, but I did forget to mention my url may have other values in it. Please see my update on my question.
Why does it already have values in it? If you're building up the parameters, simply build your query data array and then use http_build_query() once at the end - anyway, I've edited my answer to address this caveat
Did you see my update? It's pulling my current URL, and replacing certain values from it as required, not all of them. Hope that makes sense. :)
sorry, I missed that - there is probably a better way, still - using $_SERVER['REQUEST_URI'] to get the URI without the querystring, and priming the $querydata array from $_GET first...
Thanks yea that's what I though. I've been writing code for hours now and still can't wrap my brain around it. :).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.