douyuepi6485 2010-06-09 00:40
浏览 109
已采纳

如何在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"
  • 写回答

5条回答 默认 最新

  • dppi5167 2010-06-09 01:12
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序