Search code examples
phpquery-stringqsa

How to combine query strings in PHP


Given a url, and a query string, how can I get the url resulting from the combination of the query string with the url?

I'm looking for functionality similar to .htaccess's qsa. I realize this would be fairly trivial to implement completely by hand, however are there built-in functions that deal with query strings which could either simplify or completely solve this?

Example input/result sets:

Url="http://www.example.com/index.php/page?a=1"
QS ="?b=2"
Result="http://www.example.com/index.php/page?a=1&b=2"

-

Url="page.php"
QS ="?b=2"
Result="page.php?b=2"

Solution

  • How about something that uses no PECL extensions and isn't a huge set of copied-and-pasted functions? It's still a tad complex because you're splicing together two query strings and want to do it in a way that isn't just $old .= $new;

    We'll use parse_url to extract the query string from the desired url, parse_str to parse the query strings you wish to join, array_merge to join them together, and http_build_query to create the new, combined string for us.

    // Parse the URL into components
    $url = 'http://...';
    $url_parsed = parse_url($url);
    $new_qs_parsed = array();
    // Grab our first query string
    parse_str($url_parsed['query'], $new_qs_parsed);
    // Here's the other query string
    $other_query_string = 'that=this&those=these';
    $other_qs_parsed = array();
    parse_str($other_query_string, $other_qs_parsed);
    // Stitch the two query strings together
    $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed);
    $final_query_string = http_build_query($final_query_string_array);
    // Now, our final URL:
    $new_url = $url_parsed['scheme'] 
             . '://'
             . $url_parsed['host'] 
             . $url_parsed['path'] 
             . '?'      
             . $final_query_string;