2013-05-01 94 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"; 
    } 
}