看看PHP PECL 的 http_build_url。文档页面说:
建立一个网址。
第二个 URL 的部分将根据 flags 参数合并到第一个中。
添加:
如果您没有安装 PECL,我们可以跳过一些障碍。在我们尝试重建新 URL 之前,这种方法有些可靠。股票 PHP(减去 PECL)没有parse_url()
. 更难的是,parse_url()
从生成的部件数组中的 URL 中删除一些语法,因此我们必须在重新组装时将它们放回原处。http_build_url()
可以为我们解决这个问题,但如果它可用,您将不会阅读这部分内容,因为这是我最初推荐的内容。无论如何,这是代码:
<?php
/**
* addQueryParam - given a URL and some new params for its query string, return the modified URL
*
* @see http://us1.php.net/parse_url
* @see http://us1.php.net/parse_str
* @throws Exception on bad input
* @param STRING $url A parseable URL to add query params to
* @param MIXED $input_query_vars - STRING of & separated pairs of = separated key values OR ASSOCIATIVE ARRAY of STRING keys => STRING values
* @return STRING new URL
*/
function addQueryParam ($url, $input_query_vars) {
// Parse new parameters
if (is_string($input_query_vars)) {
parse_str($input_query_vars, $input_query_vars);
}
// Ensure array of parameters now available
if (!is_array($input_query_vars)) {
throw new Exception(__FUNCTION__ . ' expects associative array or query string as second parameter.');
}
// Break up given URL
$url_parts = parse_url($url);
// Test for proper URL parse
if (!is_array($url_parts)) {
throw new Exception(__FUNCTION__ . ' expects parseable URL as first parameter');
}
// Produce array of original query vars
$original_query_vars = array();
if (isset($url_parts['query']) && $url_parts['query'] !== '') {
parse_str($url_parts['query'], $original_query_vars);
}
// Merge new params inot original
$new_query_vars = array_merge($original_query_vars, $input_query_vars);
// replace the original query string
$url_parts['query'] = http_build_query($new_query_vars);
// Put URL grammar back in place
if (!empty($url_parts['scheme'])) {
$url_parts['scheme'] .= '://';
}
if (!empty($url_parts['query'])) {
$url_parts['query'] = '?' . $url_parts['query'];
}
if (!empty($url_parts['fragment'])) {
$url_parts['fragment'] = '#' . $url_parts['fragment'];
}
// Put it all back together and return it
return implode('', $url_parts);
}
// Your demo URLs
$url1 = 'http://domain.com/';
$url2 = 'http://domain.com/index.html?name=jones';
//Some usage (I did this from CLI)
echo $url1, "\n";
echo addQueryParam($url1, 'tag=xyz'), "\n";
echo addQueryParam($url1, array('tag' => 'xyz')), "\n";
echo $url2, "\n";
echo addQueryParam($url2, 'tag=xyz'), "\n";
echo addQueryParam($url2, array('tag' => 'xyz')), "\n";
echo addQueryParam($url2, array('name' => 'foo', 'tag' => 'xyz')), "\n";