In the function below, I will show you how to add a parameter in URL by treating all possible cases :
- first check whether the parameter is already defined in the URL so that we can just update it
- if parameter is already defined in the URL, so replace the parameter value, rather than append it to the end.
- else, can simply append to the end of the URL, once we know whether this is the only parameter in there or not.
1 2 3 4 5 6 7 8 9 |
function addURLParameter ($url, $paramName, $paramValue){ if (preg_match('/[?&]('.$paramName.')=[^&]*/', $url)) { $url = preg_replace('/([?&]'.$paramName.')=[^&]*/', '$1='.$paramValue, $url); }else{ $url .= strpos($url, '?') ? '&' : '?'; $url .= $paramName . '=' . $paramValue; } return $url ; } |
first check whether the parameter is already defined in the URL so that we can just update it
No comments yet.