简单的 PHP strpos 函数不起作用,为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4858927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple PHP strpos function not working, why?
提问by Daniel
Why isn't this standalone code working:
为什么这个独立代码不起作用:
$link = 'https://google.com';
$unacceptables = array('https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png');
foreach ($unacceptables as $unacceptable) {
if (strpos($link, $unacceptable) === true) {
echo 'Unacceptable Found<br />';
} else {
echo 'Acceptable!<br />';
}
}
It's printing acceptable every time even though https is contained within the $link
variable.
即使 https 包含在$link
变量中,每次打印都可以接受。
回答by coreyward
When in doubt, read the docs:
如有疑问,请阅读文档:
[strpos] Returns the numeric position of the first occurrence of needle in the haystack string.
[strpos] 返回 haystack 字符串中第一个出现针的数字位置。
So you want to try something more like:
所以你想尝试更像:
// ...
if (strpos($link, $unacceptable) !== false) {
Because otherwise strpos
is returning a number, and you're looking for a boolean true
.
因为否则strpos
会返回一个数字,而您正在寻找一个 boolean true
。
回答by acrosman
strpos()does not return true when it finds a match, it returns the position of the first matching string. Watchout, if the match is a the beginning of the string it will return an index of zero which will compare as equal to false unless you use the === operator.
strpos()在找到匹配项时不返回 true,它返回第一个匹配字符串的位置。注意,如果匹配是字符串的开头,它将返回零索引,除非您使用 === 运算符,否则该索引将比较为等于 false。
回答by Foo Bah
Your failure condition is wrong.
你的失败条件是错误的。
strpos returns false if match is not found, so you need to explicitly check
如果找不到匹配,strpos 返回 false,因此您需要明确检查
if (strpos($link, $unacceptable) !== false) {
回答by Manish Trivedi
Strpos always return position like you search "httpsL" in your string('https://google.com';) then it return 0th position and PHP evaluate it as false.
Strpos 总是返回位置,就像您在字符串('https://google.com';)中搜索“httpsL”一样,然后它返回第 0 个位置,PHP 将其评估为 false。
please see this link:(Hope its very usefull for you): http://php.net/manual/en/function.strpos.php
请参阅此链接:(希望它对您非常有用):http: //php.net/manual/en/function.strpos.php
回答by Aniket B
strpos
链轮
function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
函数可能返回布尔值 FALSE,但也可能返回计算结果为 FALSE 的非布尔值。
So I did like this
所以我喜欢这个
if (strpos($link, $unacceptable) !== false) {
//Code
}