【发布时间】:2011-05-05 06:32:32
【问题描述】:
我发现这个函数可以将参数添加或更新到给定的 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
提前致谢。
【问题讨论】:
-
该功能对我来说看起来不错。你能举一个你试图替换的参数的例子,你得到了什么结果?
-
@Bruce Alderman 示例已添加,谢谢。
-
我不确定出了什么问题;我在这里进行了几次测试,但无法重现该错误。无论如何,如果您不了解正则表达式,它们将不是最好的解决方案。当您需要维护代码时会发生什么?