PHP的5 strpos()返回0和false之间的区别? [英] php 5 strpos() difference between returning 0 and false?

查看:145
本文介绍了PHP的5 strpos()返回0和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 return 0 when there is a match at the beginning of the string
  • and it will return false when there is no match

问题是您不应该使用==来比较0false;您应该像这样使用===:

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,则
  • $a == $b将为TRUE.
  • 如果$a等于$b,并且它们具有相同的类型,则
  • $a === $b将是TRUE.
  • $a == $b will be TRUE if $a is equal to $b.
  • $a === $b will be TRUE 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 to FALSE, such as 0 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆