PHP的5 strpos()返回0和false之间的区别? [英] php 5 strpos() difference between returning 0 and false?
问题描述
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}
这在php 5上也可以通过,因为据我所知strpos返回false,它表示为0.
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?
推荐答案
是的,这是正确的/预期的行为:
Yes, this is correct / expected behavior :
-
当字符串开头存在匹配项时,
-
strpos
可以返回0
- ,如果没有匹配项,它将返回
false
strpos
can return0
when there is a match at the beginning of the string- and it will return
false
when there is no match
问题是您不应该使用==
来比较0
和false
;您应该像这样使用===
:
The thing is you should not use ==
to compare 0
and false
; you should use ===
, like this :
if(strpos("abcdefghijklmnop","http://www.") === 0) {
}
或:
if(strpos("abcdefghijklmnop","http://www.") === false) {
}
有关更多信息,请参见比较运算符:
For more informations, see Comparison Operators :
-
如果
-
$a == $b
将为TRUE
.
如果 -
$a === $b
将是TRUE
.
$a
等于$b
,则$a
等于$b
,并且它们具有相同的类型,则$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.
然后引用 strpos
的手册页:
And, quoting the manual page of strpos
:
此函数可能返回布尔值
FALSE
,但也可能返回一个 非布尔值,其计算结果为FALSE
,例如0
或""
.
请 请阅读布尔值部分 更多信息.
使用===
运算符以测试退货 该函数的值.
This function may return Boolean
FALSE
, but may also return a non-Boolean value which evaluates toFALSE
, such as0
or""
.
Please read the section on Booleans for more information.
Use the===
operator for testing the return value of this function.
这篇关于PHP的5 strpos()返回0和false之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!