将 strpos() 与 >=0 或 == false 进行松散比较并不总是返回正确的结果
我只是想弄清楚这一点...
$mystring = "/abc/def/hij";
$find = "/abc";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) >= 0) {
echo("found");
} else {
echo("not found");
}
这将给出:
0
found
$mystring = "/abc/def/hij";
$find = "/fffff";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) >= 0) {
echo("found");
} else {
echo("not found");
}
输出:
[blank]
found
现在如果我更改比较器并使用 != False
而不是 >= 0
:
$mystring = "/abc/def/hij";
$find = "/fffff";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) != false) {
echo("found");
} else {
echo("not found");
}
这几乎适用于所有情况,除了当我在字符串开头查找子字符串时。
这将输出“未找到”:
$mystring = "/abc/def/hij";
$find = "/abc";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) != false) {
echo("found");
} else {
echo("not found");
}
那么我怎样才能使其工作呢? 我只想知道字符串中是否存在子字符串,如果子字符串是开头还是整个字符串,它应该给我 true
。
I'm just trying to figure this out...
$mystring = "/abc/def/hij";
$find = "/abc";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) >= 0) {
echo("found");
} else {
echo("not found");
}
this will give :
0
found
$mystring = "/abc/def/hij";
$find = "/fffff";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) >= 0) {
echo("found");
} else {
echo("not found");
}
output:
[blank]
found
Now if I change the comparator and use != False
instead of >= 0
:
$mystring = "/abc/def/hij";
$find = "/fffff";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) != false) {
echo("found");
} else {
echo("not found");
}
This works in almost all cases, except when I look for the substring at the beginning of the string.
This will output "not found":
$mystring = "/abc/def/hij";
$find = "/abc";
echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) != false) {
echo("found");
} else {
echo("not found");
}
So how can I make that work? I just want to know if a substring exists in a string, and it should give me true
if the substring is the beginning or the entire string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
!==
运算符进行测试。 这将比较类型和值,而不是仅比较值:Test using the
!==
operator. This will compare types and values, as opposed to just values:我发现问题是什么...我需要使用 !== false 而不是 != ...啊啊,php。
I found what the problem was... I need to use !== false instead of != ... Aaaah, php.