2010-11-04 10 views
6

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.

+0

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? –

+0

@Bruce Alderman ejemplo añadido gracias. –

+0

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? –

Respuesta

18

¿Por qué no utilizar las funciones estándar de PHP para trabajar con 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)); 
} 

En este momento no se dio cuenta de que http_build_url es PECL :-) vamos a rodar nuestra propia función build_url a continuación.

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

gracias pero estoy en un host compartido que no tiene PECL –

+0

Variante no-PECL agregada – Qwerty

+0

@Sherif actualizó su respuesta. +1, esto es bueno (aunque debería estar en la pregunta original y no aquí en el duplicado, por el bien de las generaciones futuras) –

Cuestiones relacionadas