php strpos() 返回 0 和 false 之间的区别?
if(strpos("http://www.example.com","http://www.")==0){ // do work}
我希望这能解决为真,事实确实如此。但是当我这样做时会发生什么
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
这也传递了 php 5,因为据我所知,strpos 返回 false,翻译为 0。
这是正确的想法/行为吗?如果是这样,测试子字符串是否位于另一个字符串开头的解决方法是什么?
if(strpos("http://www.example.com","http://www.")==0){ // do work}
I'd expect this to resolve as true, which it does. But what happens when I do
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.
Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,这是正确/预期的行为:
strpos
可以返回0
false
当没有匹配时事情是你不应该使用
==
来比较0
和false
;你应该使用===
,像这样:或者:
有关详细信息,请参阅比较运算符:
$a如果
将为$a
等于$b
,则 == $bTRUE
。$a
等于$b
,并且 $a === $b 将为TRUE
>它们属于同一类型。并且,引用
strpos
的手册页:Yes, this is correct / expected behavior :
strpos
can return0
when there is a match at the beginning of the stringfalse
when there is no matchThe thing is you should not use
==
to compare0
andfalse
; you should use===
, like this :Or :
For more informations, see Comparison Operators :
$a == $b
will beTRUE
if$a
is equal to$b
.$a === $b
will beTRUE
if$a
is equal to$b
, and they are of the same type.And, quoting the manual page of
strpos
:===
和!==
比较类型和值,如下所示:===
and!==
compare type and value as shown below:strpos 返回一个 int 或 boolean false。 == 运算符还将 0 计算为 false,您需要使用 === 运算符(三个等号)来检查要比较的类型是否相同,而不仅仅是查看它们是否可以被计算为表示相同。
所以
strpos returns an int or boolean false. the == operator also evaluates 0 to mean false, you want to use the === operator (three equals signs) that also checks that the types being compared are the same instead of just seeing if they can be evaluated to mean the same.
so
0
是strpos
在开头找到匹配项时可能返回的值。如果未找到匹配项,则返回 false(布尔值)。因此,您需要使用===
运算符检查strpos
的返回值,该运算符检查值和类型,而不是使用==
运算符只是检查值。0
is a possible return value fromstrpos
when it finds a match at the very beginning. In case if the match is not found it returnsfalse
(boolean). So you need to check the return value ofstrpos
using the===
operator which check the value and the type rather than using==
which just checks value.我个人倾向于使用这种方式:
或者
避免使用“
0
”位置,然后始终将其设置为大于0
的数字干杯
I personally tend to use this way :
or
to avoid the "
0
" position then always make it a number more than0
cheers