2012-09-13 85 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