将http添加到字符串中-使用PHP将其转换为URL


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

我正在建立一个网站,我向用户询问Facebook和Twitter的URL,但在典型的用户时尚中,我可能只是得到一个用户名,即Twitter stackoverflow

我希望为facebook和twitter创建一个字符串

如果用户输入koodoocreative作为Twitter字符串,我会将其转换为…

http://www.twitter.com/koodoocreative

Facebook也是一样,我要创建URL

http://www.facebook.com/koodoocreative

我可以检查一下http://是否添加了吗?

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

strpos的第一种方式

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

preg_match的另一种方法:

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

我会使用parse_url和http_build_url函数。

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

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