在我的网站上,用户可以在他们的个人资料中放置一个URL。
这个URL可以是http://www.google.com
或www.google.com
或google.com
。
如果我只是在我的PHP代码中插入<a href="$url">$url</a>
,链接并不总是绝对的。
如何强制a
标记为绝对?
在我的网站上,用户可以在他们的个人资料中放置一个URL。
这个URL可以是http://www.google.com
或www.google.com
或google.com
。
如果我只是在我的PHP代码中插入<a href="$url">$url</a>
,链接并不总是绝对的。
如何强制a
标记为绝对?
//
,将被视为绝对路径。例如:<a href="//google.com">Google</a>
。https://path/to/page
,则生成的URL将为https://google.com
)。使用协议,最好是http://
<a href="http://www.google.com">Google</a>
要求用户以此格式输入网址,如果未添加,请连接 http:// 。
如果只使用前缀 //
,它将使用与页面提供服务的相同协议。
<a href="//google.com">Google</a>
我最近也需要做类似的事情。
if (strpos($url, 'http') === false) {
$url = 'http://' .$url;
}
$http_pattern = "/^http[s]*:\/\/[\w]+/i";
if (!preg_match($http_pattern, $url, $match)){
$url = 'http://' .$url;
}
"/^https?:\/{2}\w/i"
。 - eddy85br
http://
(或协议相对链接的//
)。 - Pekka