php 如何强制 HTML 链接为绝对链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17147126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:22:25  来源:igfitidea点击:

How to force an HTML link to be absolute?

phphtmlanchorrelative-pathabsolute-path

提问by Arnaud

In my website, users can put an URL in their profile.

在我的网站中,用户可以在他们的个人资料中放置一个 URL。

This URL can be http://www.google.comor www.google.comor google.com.

此 URL 可以是http://www.google.comwww.google.comgoogle.com

If I just insert in my PHP code <a href="$url">$url</a>, the link is not always absolute.

如果我只是在我的 PHP 代码中插入<a href="$url">$url</a>,链接并不总是绝对的。

How can I force the atag to be absolute ?

我怎样才能强制a标签是绝对的?

回答by Marco Chiappetta

If you prefix the URL with //it will be treated as an absolute one. For example:

如果您在 URL 中添加前缀//,它将被视为绝对地址。例如:

<a href="//google.com">Google</a>.

<a href="//google.com">Google</a>.

Keep in mind this will use the same protocol the page is being served with (e.g. if your page's URL is https://path/to/pagethe resulting URL will be https://google.com).

请记住,这将使用与提供页面相同的协议(例如,如果您的页面的 URL 是https://path/to/page结果 URL 将是https://google.com)。

回答by StephanieQ

I recently had to do something similar.

我最近不得不做类似的事情。

if (strpos($url, 'http') === false) {
    $url = 'http://' .$url;
}

Basically, if the url doesn't contain 'http' add it to the front of the string (prefix).

基本上,如果 url 不包含 'http' 将它添加到字符串的前面(前缀)。

Or we can do this with RegEx

或者我们可以用 RegEx 做到这一点

$http_pattern = "/^http[s]*:\/\/[\w]+/i";

if (!preg_match($http_pattern, $url, $match)){  
   $url = 'http://' .$url;
}  

Thank you to @JamesHilton for pointing out a mistake. Thank you!

感谢@JamesHilton 指出错误。谢谢!

回答by sinhayash

Use a protocol, preferably http://

使用协议,最好是http://

<a href="http://www.google.com">Google</a>

Ask users to enter url in this format, or concatenate http:// if not added.

要求用户以这种格式输入 url,如果未添加,则连接 http://。