2013-05-01 62 views
2

我即將建立一個自動將&pni=something放在URL後面的系統。這將是容易,如果該URL僅僅是http://t.co/something.php用「?PNI = ......」,但用戶也可以有http://t.co/something.php?myown=paramater然後系統應該增加&而不是?獲得正確url的魔術?

我怎樣才能把pni URL後面的參數並且每次都有效?我試過這個沒有運氣。

<?php 
function nice($in){ 
    $out = parse_url($in); 
    return $out['scheme'] . "://" . $out['host'] . $out['path'] . "?" . $out['query']; 
} 

$urls = array(
    "http://t.co/something.php?w=23&", 
    "http://t.co/something.php?w=23&dfdf=", 
    "http://t.co/something.php?", 
    "http://t.co/something.php", 
    "http://t.co/something", 
    "http://t.co/something.php?w=23&dfdf=34&hvem", 
); 

foreach ($urls as $url): 
    echo print_r(nice($url)) . "<br/>"; 
endforeach; 
?> 
+1

[http_build_query](http://php.net/manual/en/function.http-build-query.php)沒有做你想做的事嗎? – naththedeveloper 2013-05-01 13:49:54

+0

這已經[問及回答](http://stackoverflow.com/q/16013703)。 – HamZa 2013-05-01 13:53:11

回答

5
function nice($in) { 
    $out = parse_url($in); 
    if ($out['query'] != "") { 
     $out['query'] = "pni=something&".$out['query']; 
    } 
    else { 
     $out['query'] = "pni=something"; 
    } 

    return $out['scheme'] . "://" . $out['host'] . $out['path'] . "?" . $out['query']; 
} 
+0

時,我完全一樣,它輸出http://t.co/something.php?w=23&&pni= something1 http://t.co/something.php?w=23&dfdf=&pni=something1 http://t.co/something.php?pni=something1 http://t.co/something.php? pni = something1 http://t.co/something?pni=something1 http://t.co/something.php?w=23&dfdf=34&hvem&pni=something1「hvem」應該是hvem =&而不是hvem&和相同因爲「?w = 23 && pni = something1」應該是「?w = 23&pni = something1」 – jesper 2013-05-01 13:53:43

+0

做了一個小小的編輯,現在也應該與時髦的網址一起工作 – nvanesch 2013-05-01 13:56:20

0

您可以使用專門

$_SERVER['QUERY_STRING'] 

如果是空的訪問查詢字符串,你可以使用

$url .= '?arg=val'; 

如果查詢字符串!空

$url .= '&arg=val'; 
+0

難道你不是指'$ url。= ....'? – andrewsi 2013-05-01 13:57:33

+0

哈哈是的,我做...今天很多JS ...:/ – 2013-05-01 14:01:03

+0

當我切換PHP和perl – andrewsi 2013-05-01 14:04:41

0

檢查是否有在URL和CONCAT的pni=something給它相應的任何"?"

function nice($url){ 
    if(strpos($url,"?")!==false){ 
     return $url."&pni=something"; 
    }else{ 
     return $url."?pni=something"; 
    } 
}