【问题标题】:Remove "http://" from URL string从 URL 字符串中删除“http://”
【发布时间】:2012-09-13 22:41:28
【问题描述】:

我正在为我的自定义域使用 bit.ly 缩短器。它输出http://shrt.dmn/abc123;但是,我希望它只输出shrt.dmn/abc123

这是我的代码。

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

【问题讨论】:

    标签: php string


    【解决方案1】:

    只要它应该是 url 并且如果有 http:// - 那么这个解决方案是最简单的:

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

    【讨论】:

    • 谢谢你,zerkms。当谈到 PHP 时,我并不完全了解。我应该把那行代码放在哪里?
    • @Christopher Burton:可能在$url = get_permalink(); 行之后
    • 现在什么都不输出了。
    • 使用@Nelson 的解决方案。感谢您的帮助。
    【解决方案2】:

    更改以下行:

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

    对于这个:

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

    【讨论】:

    • 工作就像一个魅力。谢谢你,@Nelson!
    【解决方案3】:

    你想做一个 preg_replace。

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

    你也可以使用 $variable = str_replace('http://', '', $variable ) 来达到同样的效果

    【讨论】:

    • 对于这么简单的事情来说,RE 太复杂了。
    • 我对“这是未经测试的,..”位投了反对票。在将其作为答案发布之前,请花时间确保您的解决方案确实有效。
    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 2014-08-26
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2014-01-18
    • 2011-02-02
    相关资源
    最近更新 更多