如何在 PHP 中组合查询字符串 [英] How to combine query strings in PHP
问题描述
给定一个 url 和一个查询字符串,我怎样才能得到查询字符串和 url 组合得到的 url?
Given a url, and a query string, how can I get the url resulting from the combination of the query string with the url?
我正在寻找类似于 .htaccess 的 qsa
的功能.我意识到完全手动实现会相当简单,但是是否有处理查询字符串的内置函数可以简化或完全解决这个问题?
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?
示例输入/结果集:
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"
推荐答案
不使用 PECL 扩展并且没有大量复制和粘贴函数的东西怎么样?它仍然有点复杂,因为您将两个查询字符串拼接在一起,并且希望以不只是 $old .= $new;
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;
我们将使用 parse_url 来提取查询来自所需 url 的字符串,parse_str 解析查询字符串您希望加入,array_merge 将它们连接在一起,并且http_build_query 为我们创建新的组合字符串.
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;
这篇关于如何在 PHP 中组合查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!