strpos() === true 即使存在匹配也会返回 false [重复]

问题描述 投票:0回答:5

我有这个:

$fi2 = "/var/www/server/poll/ips.txt"; //IP file
$mystring = $_SERVER['REMOTE_ADDR']; //IP according to server
$findme = file_get_contents($fi2);
$pos = strpos($mystring, $findme);
if ($pos === true) {
    echo "Found";
} else {    
    echo "not found"; 
}

但是,即使 IP 与文本文件中的某些内容匹配,它也不会说“未找到”。我已经做到了

echo "$mystring $findme"; 

它正确输出我的 IP 和文本文件。

有人告诉我应该更换

if ($pos === true) {

if ($pos !== false) {

我已经这样做了,但仍然不起作用。

这是我用来保存到文本文件的代码:

//Record IP
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file
php strpos
5个回答
2
投票

我认为这是三个问题的结合。

首先,如果您正在加载的文件的 IP 地址末尾有一个新行,则它将不匹配:

$findme = file_get_contents($fi2);

更改为

$findme = trim(file_get_contents($fi2));

也正如其他人指出的那样,你的 pos 逻辑是不正确的。

if ($pos !== false) {

编辑:

你的 strpos 参数顺序也是错误的:

$pos = strpos($findme, $mystring);

1
投票

直接从手册上

strpos()

返回针相对于 haystack 字符串开头的位置(与偏移量无关)。另请注意,字符串位置从 0 开始,而不是 1。

如果未找到针,则返回

FALSE

所以结果是一个数字位置或

FALSE
,这意味着
$pos === true
always失败!另一个问题是
strpos()
的签名如下:

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

您混淆了

$haystack
$needle
,这可能是由于命名不当造成的。尝试这样的事情:

$fi2 = "/var/www/server/poll/ips.txt"; //IP file
$ip = $_SERVER['REMOTE_ADDR']; //IP according to server
$file = file_get_contents($fi2);
$pos = strpos($file, $ip);// ($findme, $mystring)
if ($pos !== FALSE) {
    echo "found";
} else {
    echo "not found";
}

0
投票

strpos
返回一个数字,如果未找到则返回
false

正确的 if 语句是:

if ($pos !== false) {

另一个常见错误是这样写:

if (!$pos) {

但是如果

$pos
0
- 如果在字符串的开头找到该字符串,则会发生这种情况 - 此检查也会失败。


0
投票

if 语句的替代方案:

if(!is_bool($pos)){

0
投票

我自己才弄清楚。

我变了

file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file

file_put_contents($fi2, "$mystring", FILE_APPEND); //Stick it onto the IP file

我不知道为什么会修复它(刚刚启动 PHP),但这就是它被破坏的原因,所以如果有人提出用原始行修复它的答案,我会接受它。

还需要将

$pos === true
更改为
$pos !== false

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.