StuBlackett
StuBlackett

Reputation: 3857

Add http to a string - Convert it to a URL using PHP

I am building a site where I am asking users for Facebook and Twitter URL's but in typical user fashion I may just get a username i.e for Twitter stackoverflow.

I am looking to create a string for both facebook and twitter

So if the user typed koodoocreative for the Twitter string, I would convert it to...

http://www.twitter.com/koodoocreative

Same with Facebook, I would essentially create the URL

http://www.facebook.com/koodoocreative

Can I also check if the http:// has been added or not?

Thanks in advance.

Upvotes: 0

Views: 408

Answers (2)

A Boy Named Su
A Boy Named Su

Reputation: 198

I would use the parse_url and http_build_url functions.

http://www.php.net//manual/en/function.parse-url.php

http://www.php.net//manual/en/function.http-build-url.php

Upvotes: 0

Bora
Bora

Reputation: 10717

$url = 'www.twitter.com/koodoocreative';

First Way with strpos

if (strpos($url, 'http') === 0) 
{
    // http prefix not found
    $url = "http://" . $url; // http://www.twitter.com/koodoocreative
}

Another Way with preg_match:

if (!preg_match("~^(?:f|ht)tps?://~i", $url)) 
{
    // http prefix not found
    $url = "http://" . $url; // http://www.twitter.com/koodoocreative
}

Upvotes: 1

Related Questions