2012-09-13 83 views
1

我對自定義域使用了bit.ly縮寫。它輸出http://shrt.dmn/abc123;不過,我想只輸出shrt.dmn/abc123從URL字符串中刪除「http://」

這是我的代碼。

//automatically create bit.ly url for wordpress widgets 
function bitly() 
{ 
    //login information 
    $url = get_permalink(); //for wordpress permalink 
    $login = 'UserName'; //your bit.ly login 
    $apikey = 'API_KEY'; //add your bit.ly APIkey 
    $format = 'json'; //choose between json or xml 
    $version = '2.0.1'; 
    //generate the URL 
    $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format; 

    //fetch url 
    $response = file_get_contents($bitly); 
//for json formating 
    if(strtolower($format) == 'json') 
    { 
    $json = @json_decode($response,true); 
    echo $json['results'][$url]['shortUrl']; 
    } 
    else //for xml formatting 
    { 
    $xml = simplexml_load_string($response); 
    echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash; 
    } 
} 

回答

3

更改下面一行:

echo $json['results'][$url]['shortUrl']; 

爲這一個:

echo substr($json['results'][$url]['shortUrl'], 7); 
+0

像魅力一樣工作。謝謝@納爾遜! –

+0

歡迎您! :-) – Nelson

+0

如果它的https? – wesside

5

只要它應該是URL,如果有http:// - 那麼這個解決方案是最簡單的可能:

$url = str_replace('http://', '', $url); 
+0

謝謝你,zerkms。談到PHP時,我並不完全知識淵博。我會在哪裏放這行代碼? –

+0

@Christopher Burton:也許在'$ url = get_permalink();'line – zerkms

+0

之後現在它不輸出任何東西。 –

-1

你想做一個preg_replace。

$variable = preg_replace('/http:\/\//', '', $variable); (this is untested, so you might also need to escape the : character). 

還可以實現與$變量相同的效果= str_replace函數(的 'http://', '',$變量)

+2

RE對於這麼簡單的事情是如此複雜。 – Zaffy

+1

我低估了「這是未經測試的,..」位。請花時間確保您的解決方案在將其發佈爲答案之前實際發揮作用。 – NotMe