2011-09-09 20 views
6

Ok .. Quindi, fondamentalmente, diciamo che abbiamo un link:modo migliore per sostituire il valore della stringa di query in un dato url

$url = "http://www.site.com/index.php?sub=Mawson&state=QLD&cat=4&page=2&sort=z"; 

Fondamentalmente, ho bisogno di creare una funzione, che sostituisce ogni cosa nella URL, per esempio:

<a href="<?=$url;?>?sort=a">Sort by A-Z</a> 
<a href="<?=$url;?>?sort=z">Sort by Z-A</a> 

Oppure, per un altro esempio:

<a href="<?=$url;?>?cat=1">Category 1</a> 
<a href="<?=$url;?>?cat=2">Category 2</a> 

Oppure, un altro esempio:

<a href="<?=$url;?>?page=1">1</a> 
<a href="<?=$url;?>?page=2">2</a> 
<a href="<?=$url;?>?page=3">3</a> 
<a href="<?=$url;?>?page=4">4</a> 

Quindi, in pratica, abbiamo bisogno di una funzione che andrà a sostituire la specifica $_GET dall'URL in modo che non si ottiene un duplicato, come ad esempio: ?page=2&page=3

Detto questo, ha bisogno di essere intelligente, quindi sa se l'inizio del parametro è un ? o un &

abbiamo anche bisogno di essere intelligente in modo che possiamo avere l'URL in questo modo:

<a href="<?=$url;?>page=3">3</a> (without the ? - so it will detect automatically wether to use an `&` or a `?` 

Non mi interessa creare variabili diverse per ogni preg_replace per i determinati parametri $ _GET, ma sto cercando il modo migliore per farlo.

Grazie.

+1

non analizzano HTML con regex (http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Invece, analizza il DOM (http://stackoverflow.com/questions/3650125/how-to-parse-html-with-php). –

+0

Spiacente non posso aiutare, ma puoi testare regexp qui: http://regexpal.com/ E per assistenza su php preg sostituire ecc: http://www.regular-expressions.info/php.html Spiacente non potrei aiutare di più – 422

+0

I avere re-tag e rendere il titolo appropriato alla descrizione e al problema forniti. Si prega di rivedere – ajreal

risposta

9

Che ne dici di qualcosa del genere?

function merge_querystring($url = null,$query = null,$recursive = false) 
{ 
    // $url = 'http://www.google.com.au?q=apple&type=keyword'; 
    // $query = '?q=banana'; 
    // if there's a URL missing or no query string, return 
    if($url == null) 
    return false; 
    if($query == null) 
    return $url; 
    // split the url into it's components 
    $url_components = parse_url($url); 
    // if we have the query string but no query on the original url 
    // just return the URL + query string 
    if(empty($url_components['query'])) 
    return $url.'?'.ltrim($query,'?'); 
    // turn the url's query string into an array 
    parse_str($url_components['query'],$original_query_string); 
    // turn the query string into an array 
    parse_str(parse_url($query,PHP_URL_QUERY),$merged_query_string); 
    // merge the query string 
    if($recursive == true) 
    $merged_result = array_merge_recursive($original_query_string,$merged_query_string); 
    else 
    $merged_result = array_merge($original_query_string,$merged_query_string); 
    // Find the original query string in the URL and replace it with the new one 
    return str_replace($url_components['query'],http_build_query($merged_result),$url); 
} 

utilizzo ...

<a href="<?=merge_querystring($url,'?page=1');?>">Page 1</a> 
<a href="<?=merge_querystring($url,'?page=2');?>">Page 2</a> 
+0

È piuttosto semplice, trasforma i parametri della stringa di query dalla fine dell'URL in una matrice, quindi trasforma il secondo parametro in una matrice, unisce i due array (quindi il secondo set si sovrapporrà al primo set) quindi gira la array di nuovo in una stringa di query, quindi trovare e sostituisce la stringa di query originale con la nuova stringa compilata. Quello che non ho codificato è stato se non ci fosse alcuna stringa di query sul valore URL iniziale, a quel punto potrei fare in modo che la funzione aggiungesse semplicemente la nuova stringa di query. – Scuzzy

+0

Come facciamo a farlo funzionare così se non ci sono parametri $ _GET, funzionerà ancora? Ad esempio: http://www.site.com/index.php e quindi un collegamento creato per http://www.site.com/index.php?sort=a (come quando lo sto facendo al momento, se ci sono non è $ _GET, quindi l'ordinamento = a non è stato aggiunto. – Latox

+0

Ho accettato la tua risposta, ma ottenere questo funzionamento senza alcun parametro $ _GET sarebbe perfetto. – Latox

1

Se sto leggendo correttamente, e non può essere. Sai quale GET stai sostituendo in una stringa url? Questo può essere sciatto ma ...

$url_pieces = explode('?', $url); 
$var_string = $url_pieces[1].'&'; 
$new_url = $url_pieces[0].preg_replace('/varName\=value/', 'newVarName=newValue', $var_string); 

Questo è il mio introito, Buona fortuna.

1

Non so se questo è quello che stai cercando di realizzare, ma qui va comunque:

<?php 
    function mergeMe($url, $assign) { 
     list($var,$val) = explode("=",$assign); 
     //there's no var defined 
     if(!strpos($url,"?")) { 
      $res = "$url?$assign"; 
     } else { 
      list($base,$vars) = explode("?",$url); 
      //if the vars dont include the one given 
      if(!strpos($vars,$var)) { 
       $res = "$url&$assign"; 
      } else { 
       $res = preg_replace("/$var=[a-zA-Z0-9_]*(&|$)/",$assign."&",$url); 
       $res = preg_replace("/&$/","",$res); //remove possible & at the end 
      } 
     } 
     //just to show the difference, should be "return $res;" instead 
     return "$url <strong>($assign)</strong><br>$res<hr>"; 
    } 

    //example 
    $url1 = "http://example.com"; 
    $url2 = "http://example.com?sort=a"; 
    $url3 = "http://example.com?sort=a&page=0"; 
    $url4 = "http://example.com?sort=a&page=0&more=no"; 

    echo mergeMe($url1,"page=4"); 
    echo mergeMe($url2,"page=4"); 
    echo mergeMe($url3,"page=4"); 
    echo mergeMe($url4,"page=4"); 
?> 
+0

Hey derp, penso che sarà piuttosto lento perché usi preg_replace 2x qui – fedmich

4
<?php 
function change_query ($url , $array) { 
    $url_decomposition = parse_url ($url); 
    $cut_url = explode('?', $url); 
    $queries = array_key_exists('query',$url_decomposition)?$url_decomposition['query']:false; 
    $queries_array = array(); 
    if ($queries) { 
     $cut_queries = explode('&', $queries); 
     foreach ($cut_queries as $k => $v) { 
      if ($v) 
      { 
       $tmp = explode('=', $v); 
       if (sizeof($tmp) < 2) $tmp[1] = true; 
       $queries_array[$tmp[0]] = urldecode($tmp[1]); 
      } 
     } 
    } 
    $newQueries = array_merge($queries_array,$array); 
    return $cut_url[0].'?'.http_build_query($newQueries); 
} 
?> 

Usa come questo:

<?php 
    echo change_query($myUrl, array('queryKey'=>'queryValue')); 
?> 

me che questo mattina, sembra funzionare in ogni caso. È possibile modificare/aggiungere più di una query, con la matrice;)

5

Bene, ho avuto lo stesso problema, ho trovato questa domanda e, alla fine, ho preferito il mio metodo. Forse ha difetti, quindi per favore dimmi cosa sono. La mia soluzione è:

$query=$_GET; 
$query['YOUR_NAME']=$YOUR_VAL; 
$url=$_SERVER['PHP_SELF']. '?' . http_build_query($query); 

Speranza che aiuta.

2
function replaceQueryParams($url, $params) 
{ 
    $query = parse_url($url, PHP_URL_QUERY); 
    parse_str($query, $oldParams); 

    if (empty($oldParams)) { 
     return rtrim($url, '?') . '?' . http_build_query($params); 
    } 

    $params = array_merge($oldParams, $params); 

    return preg_replace('#\?.*#', '?' . http_build_query($params), $url); 
} 

$url esempi:

$params esempio:

[ 
    'foo' => 'not-bar', 
] 

Nota: non capisce gli URL con tasselli (hash) come http://example.com/page?foo=bar#section1

0

migliorare la funzione Scuzzy 2013 ultimi pezzi per la stringa di query url pulita.

// merge the query string 
// array_filter removes empty query array 
    if ($recursive == true) { 
     $merged_result = array_filter(array_merge_recursive($original_query_string, $merged_query_string)); 
    } else { 
     $merged_result = array_filter(array_merge($original_query_string, $merged_query_string)); 
    } 

    // Find the original query string in the URL and replace it with the new one 
    $new_url = str_replace($url_components['query'], http_build_query($merged_result), $url); 

    // If the last query string removed then remove ? from url 
    if(substr($new_url, -1) == '?') { 
     return rtrim($new_url,'?'); 
    } 
    return $new_url; 
Problemi correlati