可能重複:
Change single variable value in querystringPHP - 添加/更新參數中的URL
,我發現這個功能的參數添加或更新給定的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
如果我叫addURLParameter與L =英語,我提前得到
http://www.mysite.com/showprofile.php?id=110&l=arabic&l=english
感謝。
該函數對我來說確實很好。你能給出一個你想要替換的參數的例子,以及你得到的結果是什麼? – 2010-11-04 20:13:40
@Bruce Alderman示例添加了謝謝。 – 2010-11-04 20:49:18
我不確定有什麼問題;我在這裏運行了一對測試,但無法重現錯誤。無論如何,如果你不懂正則表達式,它們將不是最好的解決方案。當你需要維護代碼時會發生什麼? – 2010-11-05 05:07:41