Duplicar posible:
Change single variable value in querystringphp - añadir/actualizar un parámetro en una url
me encontré con esta función para añadir o actualizar un parámetro con una determinada URL, funciona cuando el parámetro necesita ser agregado, pero si el parámetro existe no lo reemplaza - lo siento, no sé mucho sobre regex ¿alguien puede echar un vistazo:
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 ;
}
He aquí un ejemplo de lo que no funciona:
http://www.mysite.com/showprofile.php?id=110&l=arabic
si llamo addURLParameter con l = Inglés, consigo
http://www.mysite.com/showprofile.php?id=110&l=arabic&l=english
gracias por adelantado.
La función me parece correcta. ¿Puedes dar un ejemplo de un parámetro que estás tratando de reemplazar y qué resultado estás obteniendo? –
@Bruce Alderman ejemplo añadido gracias. –
No estoy seguro de lo que está mal; Ejecuté un par de pruebas aquí y no pude reproducir el error. De todos modos, si no entiende las expresiones regulares, no serán la mejor solución. ¿Qué pasaría cuando necesitaras mantener el código? –