Arn*_*aud 22 html php anchor relative-path absolute-path
在我的网站中,用户可以在其个人资料中添加网址.
此URL可以是http://www.google.com或www.google.com或google.com.
如果我只是插入我的PHP代码<a href="$url">$url</a>,链接并不总是绝对的.
如何强制a标签绝对?
Mar*_*tta 31
如果您使用URL //作为前缀,则将其视为绝对URL .例如:
<a href="//google.com">Google</a>.
请记住,这将使用与提供页面相同的协议(例如,如果您的页面的URL是https://path/to/page结果URL https://google.com).
我最近不得不做类似的事情.
if (strpos($url, 'http') === false) {
$url = 'http://' .$url;
}
Run Code Online (Sandbox Code Playgroud)
基本上,如果url不包含'http',则将其添加到字符串的前面(前缀).
或者我们可以使用RegEx执行此操作
$http_pattern = "/^http[s]*:\/\/[\w]+/i";
if (!preg_match($http_pattern, $url, $match)){
$url = 'http://' .$url;
}
Run Code Online (Sandbox Code Playgroud)
感谢@JamesHilton指出错误.谢谢!
使用协议,最好是http://
<a href="http://www.google.com">Google</a>
Run Code Online (Sandbox Code Playgroud)
要求用户以此格式输入url,或者如果未添加则连接http://.
| 归档时间: |
|
| 查看次数: |
24044 次 |
| 最近记录: |