How to replace a specific value of a query string from a url through PHP using an array?

1

I have the following url that is returned to me by a webservice in a certain part of my application. But it comes with a query string that determines the size of the image (according to the parameter width that url brings me the image with different size).

I would like to be able to replace only this value of the query string, width , and replace with another.

I want to do this from a array . That is, I will have a array with the values that I want to replace in the query string of this url, but I can not remove the others.

For example. If I have this url:

 http://site.com/images/?sistema=3&size=500&type=png;

I want to transform it by transforming the value from 500 to 200 , making it like this:

 http://site.com/images/?sistema=3&size=200&type=png;

As I want to do through a array , I need something like this:

 // retornado pelo webservice

 $url = 'http://site.com/images/?sistema=3&size=500&type=png';

 $url = transforma_query_string($url, array('size' => 200));

This would have to return:

'http://site.com/images/?sistema=3&size=200&type=png;'

How could I do to create this function in PHP? Can anyone help me?

    
asked by anonymous 15.04.2016 / 18:26

2 answers

2

Specific option

function transforma_query_string($str, $parameters) {
    // considerando que a url será sempre size=500 e que outros parâmetros nunca terão o valor 500:
    return str_replace('500', $parameters['size'], $str);
}

$url = 'http://site.com/images/?sistema=3&size=500&type=png';
echo transforma_query_string($url, array('size' => 200));

Generic option

Something more generic, where you can use for different URLs:

function foo($url, $new_query) {
    $arr = parse_url($url);
    parse_str($arr['query'], $query);
    return $arr['scheme'].'://'.$arr['host'].$arr['path'].'?'.http_build_query(array_replace($query, $new_query));
}

$url = 'http://site.com/images/?sistema=3&size=500&type=png';
echo foo($url, array('size' => 200));
    
15.04.2016 / 19:13
1
function transforma_query_string($url,$dados){
   $url=explode('?',$url,2);//separa o link dos argumentos
   $link=$url[0].'?';//adiciona o ? para ficar pronto para os argumentos
   $argumentos=explode('&',$url[1]);//divide os argumentos
   foreach($argumentos AS $i){//corre todos os argumentos
       $temp=explode('=',$i);//separa o index e valor
       if (array_key_exists($temp[0],$dados)){//verifica se é para alterar
           $temp[1]=$dados[$temp[0]];//altera
       }
       $link.=$link==$url[0].'?'?$temp[0].'='.$temp[1]:'&'.$temp[0].'='.$temp[1];//Adiciona ao link
   }
   return $link;// envia o link alterado
}
    
15.04.2016 / 19:16