读取文本文件并将行与完全相同的行进行比较返回 false [英] Reading text file and comparing line with the exact same line returns false

查看:16
本文介绍了读取文本文件并将行与完全相同的行进行比较返回 false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的代码:

$file = fopen("countries.txt","r");
$array = array();

while(!feof($file)) {
    $array[] = fgets($file);
}

fclose($file);

这是我的 foreach 循环:

Here is my foreach loop:

$str = "test";

foreach ($array as $key => $val) {

    if ($val == $str) {
        echo $val;
    } else {
        echo "not found";
    }

}

我想知道为什么它只打印 $val 如果它是数组的最后一个值.

I am wondering why it is only printing $val if it is the last value of the array.

例如,如果txt文件看起来像这样就可以了

For example, it works if the txt file looks like this

test1
test2
test3
test

但如果看起来像这样就不起作用

but doesn't work if it looks like this

test1
test2
test
test3

推荐答案

问题是,你在每一行的末尾都有一个换行符,所以:

The problem is, that you have a new line character at the end of each line, so:

test\n !== test
  //^^ See here

这就是为什么它没有像您期望的那样工作.

That's why it doesn't work as you expect it to.

现在怎么解决?能不能给大家介绍一下函数:file().您可以将文件读入数组并设置标志以忽略每行末尾的这些新行.

How to solve it now? Can I introduce to you the function: file(). You can read a file into an array and set the flag to ignore these new lines at the end of each line.

所以把所有这些信息放在一起你会得到这个代码:

So putting all this information together you will get this code:

$array = file("countries.txt", FILE_IGNORE_NEW_LINES);
$str = "test";

foreach ($array as $key => $val) {

    if ($val == $str) {
        echo $val;
    } else {
        echo "not found";
    }

}

这篇关于读取文本文件并将行与完全相同的行进行比较返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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