我发现这个函数可以在给定的url中添加或更新参数,当需要添加参数时它可以正常工作,但是如果参数存在则不会替换它 - 对不起,我不太了解正则表达式可以任何人请看一下:
function addURLParameter ($url, $paramName, $paramValue) {
// first check whether the parameter is already
// defined in the URL so that we can just update
// the value if that's the case.
if (preg_match('/[?&]('.$paramName.')=[^&]*/', $url)) {
// parameter is already defined in the URL, so
// replace the parameter value, rather than
// append it to the end.
$url = preg_replace('/([?&]'.$paramName.')=[^&]*/', '$1='.$paramValue, $url) ;
} else {
// can simply append to the end of the URL, once
// we know whether this is the only parameter in
// there or not.
$url .= strpos($url, '?') ? '&' : '?';
$url .= $paramName . '=' . $paramValue;
}
return $url ;
}
这是一个不起作用的例子:
http://www.mysite.com/showprofile.php?id=110&l=arabic
如果我用l = english调用addURLParameter,我得
http://www.mysite.com/showprofile.php?id=110&l=arabic&l=english
提前感谢。
答案 0 :(得分:18)
为什么不使用标准PHP函数来处理URL?
function addURLParameter ($url, $paramName, $paramValue) {
$url_data = parse_url($url);
$params = array();
parse_str($url_data['query'], $params);
$params[$paramName] = $paramValue;
$params_str = http_build_query($params);
return http_build_url($url, array('query' => $params_str));
}
抱歉没有注意到http_build_url是PECL :-)
让我们自己推出build_url
函数。
function addURLParameter($url, $paramName, $paramValue) {
$url_data = parse_url($url);
if(!isset($url_data["query"]))
$url_data["query"]="";
$params = array();
parse_str($url_data['query'], $params);
$params[$paramName] = $paramValue;
$url_data['query'] = http_build_query($params);
return build_url($url_data);
}
function build_url($url_data) {
$url="";
if(isset($url_data['host']))
{
$url .= $url_data['scheme'] . '://';
if (isset($url_data['user'])) {
$url .= $url_data['user'];
if (isset($url_data['pass'])) {
$url .= ':' . $url_data['pass'];
}
$url .= '@';
}
$url .= $url_data['host'];
if (isset($url_data['port'])) {
$url .= ':' . $url_data['port'];
}
}
$url .= $url_data['path'];
if (isset($url_data['query'])) {
$url .= '?' . $url_data['query'];
}
if (isset($url_data['fragment'])) {
$url .= '#' . $url_data['fragment'];
}
return $url;
}