如何在PHP中组合查询字符串

Cam*_*Cam 2 php query-string qsa

给定一个url和一个查询字符串,如何获取查询字符串与url组合产生的url?

我正在寻找类似于.htaccess的功能qsa.我意识到完全手工实现这是相当简单的,但有没有内置函数处理查询字符串,可以简化或完全解决这个问题?

输入/结果集示例:

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"
Run Code Online (Sandbox Code Playgroud)

-

Url="page.php"
QS ="?b=2"
Result="page.php?b=2"
Run Code Online (Sandbox Code Playgroud)

Cha*_*les 7

那些不使用PECL扩展并且不是大量复制和粘贴功能的东西怎么样?它仍然有点复杂,因为你将两个查询字符串拼接在一起,并希望以一种不仅仅是这样的方式来实现它$old .= $new;

我们将使用parse_url从所需的url中提取查询字符串,使用parse_str解析要加入的查询字符串,使用array_merge将它们连接在一起,使用http_build_query为我们创建新的组合字符串.

// 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;
Run Code Online (Sandbox Code Playgroud)

  • +奇迹般地成为唯一一个不愿意使用适当的,随时可用的功能的人.这可能是我的一个小小的烦恼,但所有那些重新重新重新重新发明已经可用的功能的人是PHP获得糟糕代表的重要原因. (3认同)