2011-09-09 28 views
6

好吧..所以基本上說,我們有一個鏈接:更好的方式在給定的URL替換查詢字符串值

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

基本上,我需要創建一個功能,它取代在URL中每一件事情,例如:

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

或者,另一個例子:

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

或者,另一個例子:

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

因此,基本上,我們需要一個函數,它會從URL替換特定$_GET讓我們不要重複,如:?page=2&page=3

話雖如此,它需要智能,因此它知道,如果該參數的開始是?&

我們還需要的是聰明,所以我們可以有像這樣的網址:

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

我不介意爲特定的$ _GET參數爲每個preg_replace創建不同的變量,但我正在尋找最佳方法來完成此操作。

謝謝。

+1

不解析與正則表達式HTML(http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)。相反,解析DOM(http://stackoverflow.com/questions/3650125/how-to-parse-html-with-php)。 – 2011-09-09 02:58:30

+0

抱歉沒有幫助,但你可以在這裏測試正則表達式:http://regexpal.com/和幫助在PHP preg替換等:http://www.regular-expressions.info/php.html抱歉無法幫助更多 – 422

+0

我重新標記並使標題適合於給定的描述和問題。請修改 – ajreal

回答

9

這樣的事情呢?

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); 
} 

使用...

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

它非常簡單,它將查詢字符串參數從URL的末尾轉換爲數組,然後將第二個參數轉換爲數組,將兩個數組合並(因此第二個數組將覆蓋第一個數組),然後轉換將數組返回到查詢字符串中,然後查找並用新編譯的字符串替換原始查詢字符串。我沒有編碼的是,如果初始URL值沒有查詢字符串,那麼我可以使該函數追加新的查詢字符串。 – Scuzzy

+0

我們如何使這項工作,所以如果沒有任何$ _GET參數,它仍然會工作?例如:http://www.site.com/index.php,然後爲http://www.site.com/index.php?sort=a創建一個鏈接(就像我目前正在做這件事,如果有的話)是不是$ _GET,那麼排序= a不會被添加 – Latox

+0

我已經接受你的答案,但沒有任何$ _GET參數,得到這個工作將是完美的 – Latox

1

如果我正確地讀這篇文章,我可能不會。你知道你在URL字符串中取代哪個GET?這可能是馬虎,但...

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

這是我的要求,祝你好運。

1

我不知道這是否是你想完成什麼,但在這裏不言而喻反正:

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

嘿derp,我認爲這會很慢,因爲你在這裏使用preg_replace 2x – 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); 
} 
?> 

使用這樣的:

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

我這樣做,這上午,它似乎在所有情況下工作。你可以用數組更改/添加多個查詢;)

5

那麼,我有同樣的問題,發現這個問題,最後,我最喜歡自己的方法。也許它有缺陷,那麼請告訴我他們是什麼。 我的解決方案是:

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

希望它有幫助。

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例子:

$params例如:

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

:它不理解與錨(哈希)的URL像http://example.com/page?foo=bar#section1

0

改善Scuzzy 2013功能 乾淨的URL查詢字符串的最後部分。

// 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; 
相關問題