2010-11-04 97 views
6

可能重複:
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 

感謝。

+0

該函數對我來說確實很好。你能給出一個你想要替換的參數的例子,以及你得到的結果是什麼? – 2010-11-04 20:13:40

+0

@Bruce Alderman示例添加了謝謝。 – 2010-11-04 20:49:18

+0

我不確定有什麼問題;我在這裏運行了一對測試,但無法重現錯誤。無論如何,如果你不懂正則表達式,它們將不是最好的解決方案。當你需要維護代碼時會發生什麼? – 2010-11-05 05:07:41

回答

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; 
} 
+0

謝謝,但我在沒有PECL的共享主機上 – 2010-11-04 21:56:26

+0

添加了no-PECL變體 – Qwerty 2010-11-05 10:27:39

+0

@Sherif他更新了他的答案。 +1,這很好(儘管它應該在原始問題中,而不是在重複中,爲了子孫後代) – 2010-11-05 10:27:51