如果 http:// 在字符串中则保留它,否则如果不添加它
我有一个输入,您输入一个 URL,我基本上想编写一些 php 来表示如果域包含“http://”,则保留它,否则如果不包含,则将其添加到开头。 这就是我到目前为止所拥有的......
$domain = $_POST["domain"];
if (strpos($domain, "http://")) {
return $domain;
} else {
$domain = "http://" . $domain;
}
这似乎不起作用......
如果它不包含http://,它就不会添加http://。
I have a input that you enter a URL, i basically want to write some php that says if the domain containts "http://" then leave it be, else if not then add it to the beginning.
This is what I have so far...
$domain = $_POST["domain"];
if (strpos($domain, "http://")) {
return $domain;
} else {
$domain = "http://" . $domain;
}
This doesnt seem to work..
it doesnt add the http:// on if it doesnt contain http://.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您忘记返回 $domain。
you forgot to return $domain.
由于字符串以
http://
开头,因此strpos
将返回0
,其计算结果为 false。将 if 语句更改为:
Since the string starts with
http://
,strpos
will return0
, which will evaluate to false.Change the if statement to:
无论如何添加如何?我发现这样更容易:
How about adding adding it regardless? I find that to be easier:
阅读手册:
read manual:
这是因为 strpos 将返回字符串在字符串中的位置。
在你的 url 中,它是 0。这等于 false。进行严格检查 - add === false。
That is because strpos will return the location of the string, within the string.
In your url, that is 0. Which equals to false. Make it a strict check - add === false.
我知道这有点晚了,但我更喜欢这种方法:
这将保留 https:// 地址,而不会让您最终得到
http://https://www.mysite.com
。如果您有不使用 https 地址的规则,您还可以进一步编辑它以删除 https://。我知道最初的问题并没有要求这个,但我认为在大多数情况下考虑这一点很重要,并且希望能够帮助其他前来寻找的人。
I know this is a bit late to the party, but I prefer this approach:
This will preserve a https:// address, and not have you ending up with
http://https://www.mysite.com
. You could also further edit it to strip out https:// if you had a rule for not using https addresses.I know the original question didn't ask for this, but I think it's important to consider in most situations, and will hopefully help someone else who comes looking.
使用 strpos() 时要小心。当在字符串开头找到“http://”时,它将返回 0,从而导致 if 语句意外失败。您需要检查返回的类型以确保:
Use caution when using strpos(). It will return 0 when 'http://' is found at the beginning of the string, causing your if statement to fail unexpectedly. You will want to check the type of the return to be sure: