php 检查 url 开头是否有 http:// 并插入如果没有
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8591623/
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
Checking if a url has http:// at the beginning & inserting if not
提问by Rory Web Rothon
I am currently editing a wordpress theme with custom field outputs.
I have successfully made all the edits and everything works as it should.
My problem is that if a url is submitted into the custom field, the echo is exactly what was in there, so if someone enters www.somesite.com the echo is just that and adds it to the end of the domain: www.mysite.com www.somesite.com .
I want to check to see if the supplied link has the http://
prefix at the beginning, if it has then do bothing, but if not echo out http://
before the url.
我目前正在编辑带有自定义字段输出的 wordpress 主题。我已经成功地进行了所有的编辑,一切正常。我的问题是,如果将 url 提交到自定义字段中,则回声正是其中的内容,因此,如果有人输入 www.somesite.com,则回声就是这样并将其添加到域的末尾:www.mysite .com www.somesite.com 。我想检查所提供的链接是否http://
在开头有前缀,如果有则两者兼而有之,但如果没有http://
在 url 之前回显。
I hope i have explained my problem as good as i can.
我希望我已经尽可能好地解释了我的问题。
$custom = get_post_meta($post->ID, 'custom_field', true);
<?php if ( get_post_meta($post->ID, 'custom_field', true) ) : ?>
<a href="<?php echo $custom ?>"> <img src="<?php echo bloginfo('template_url');?>/lib/images/social/image.png"/></a>
<?php endif; ?>
回答by DaveRandom
parse_url()
can help...
parse_url()
可以帮助...
$parsed = parse_url($urlStr);
if (empty($parsed['scheme'])) {
$urlStr = 'http://' . ltrim($urlStr, '/');
}
回答by Tyil
You can check if http://
is at the beginning of the string using strpos().
您可以http://
使用strpos()检查是否位于字符串的开头。
$var = 'www.somesite.com';
if(strpos($var, 'http://') !== 0) {
return 'http://' . $var;
} else {
return $var;
}
This way, if it does not have http://
at the very beginning of the var, it will return http://
in front of it. Otherwise it will just return the $var
itself.
这样,如果它http://
在 var 的最开始没有,它会http://
在它前面返回。否则它只会返回$var
自身。
回答by KingCrunch
echo (strncasecmp('http://', $url, 7) && strncasecmp('https://', $url, 8) ? 'http://' : '') . $url;
Remember, that strncmp()
returns 0
, when the first n
letters are equal, which evaluates to false
here. That may be a little bit confusing.
请记住,当第一个字母相等时,它strncmp()
返回0
,n
其计算结果为false
这里。这可能有点令人困惑。