Php - add / update parameter in url

Possible duplicate:
Change the value of one variable in querystring

I found this function to add or update a parameter to a given URL, it works when the parameter needs to be added, but if the parameter exists, it does not replace it - sorry, I don’t know much about regular expression, can someone please look :

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

here is an example of what doesn't work:

 http://www.mysite.com/showprofile.php?id=110&l=arabic 

if I call addURLParameter with l = english, I get

 http://www.mysite.com/showprofile.php?id=110&l=arabic&l=english 

early.

+6
php regex
Nov 04 '10 at 19:35
source share
1 answer

Why not use the standard PHP functions for working with URLs?

 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)); } 

Sorry, didn’t notice that http_build_url is PECL :-) Let us roll our own build_url function.

 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; } 
+18
Nov 04 '10 at 21:35
source share



All Articles