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


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

我正在建立一个网站,向用户询问Facebook和Twitter URL,但以典型的用户方式,我可能只是获得一个用户名,即Twitter stackoverflow

我正在为Facebook和Twitter创建一个字符串

因此,如果用户在Twitter字符串中键入koodoocreative,我会将其转换为...

http://www.twitter.com/koodoocreative

与Facebook相同,我基本上会创建URL

http://www.facebook.com/koodoocreative

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

预先感谢。


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

strpos的第一种方式

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

preg_match的另一种方式:

1
2
3
4
5
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/zh/function.http-build-url.php