1

I am using a bit.ly shortener for my custom domain. It outputs http://shrt.dmn/abc123; however, I'd like it to just output shrt.dmn/abc123.

Here is my code.

//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 Answers 3

5

As long as it is supposed to be url and if there is http:// - then this solution is the simplest possible:

$url = str_replace('http://', '', $url);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, zerkms. I'm not entirely knowledgeable when it comes to PHP. Where would I put that line of code?
@Christopher Burton: perhaps after $url = get_permalink(); line
Now it doesn't output anything.
Used @Nelson's solution. I appreciate your help.
3

Change your following line:

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

for this one:

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

Comments

-1

You want to do a preg_replace.

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

you can also achieve the same effect with $variable = str_replace('http://', '', $variable )

2 Comments

RE is so complex for such simple thing.
I downvoted for the "this is untested, .." bit. Please take the time to ensure that your solution will actually work prior to posting it as an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.