[英]Unexpected Behavior when Parsing Text File
I am learning PHP, & right now I'm stuck. 我正在学习PHP,并且现在我陷入困境。 I am reading a .txt file in the script.
我正在脚本中读取.txt文件。 The file contents are like this:
文件内容如下:
joe:secret
root:admin
I can read the file easily using the file()
function, which returns an array. 我可以使用
file()
函数轻松地读取文件,该函数返回一个数组。 I store the data in aa variable as: 我将数据存储在a变量中为:
$data = file('location/file.txt');
Next I use foreach loop, and then I explode each line, and store its contents in a variable again. 接下来,我使用foreach循环,然后展开每一行,并将其内容再次存储在变量中。 Then I put checks on the variable, but this is where I get behavior which I don't understand.
然后,我对变量进行检查,但这是我无法理解的行为。
foreach ($data as $d) {
$row = explode(":", $d);
if ($row[0] == "joe" && $row[1] == "secret") {
echo "match found ";
}
}
The above code does give expected output. 上面的代码确实给出了预期的输出。 Why is that?
这是为什么? If I do this,
如果我这样做
echo $row[0]; echo $row[1];
then I do receive correct output. 然后我会收到正确的输出。 So I don't get why my check fails?
所以我不明白为什么我的支票失败了?
This one was tricky; 这个棘手; I don't blame you for not catching this :)
我不怪你没抓住这个:)
So first, let's investigate with the php -a
interactive shell: 因此,首先,让我们研究一下
php -a
交互式shell:
php > $data = file('test.txt');
php > var_dump($data);
array(3) {
[0]=>
string(11) "joe:secret
"
[1]=>
string(11) "root:admin
"
[2]=>
string(1) "
"
}
See how the closing quote is on a separate line? 看看结尾的报价单行如何? That's because the
\\n
's at the end of each line are kept inside each array element in $data
. 这是因为每行末尾的
\\n
保留在$data
每个数组元素内。 So $row[1]
doesn't equal "secret"
; 因此
$row[1]
不等于"secret"
; it equals "secret\\n"
. 等于
"secret\\n"
。 To fix this, all we need is rtrim()
: 为了解决这个问题,我们需要的只是
rtrim()
:
foreach ($data as $line) {
$line = rtrim($line);
$row = explode(":", $line);
if ($row[0] == "joe" && $row[1] == "secret") {
echo "Match found for joe!";
}
}
Now, it works as expected: 现在,它可以按预期工作:
php > $data = file('test.txt');
php > foreach ($data as $line) {
php { $line = rtrim($line);
php { $row = explode(":", $line);
php {
php { if ($row[0] == "joe" && $row[1] == "secret") {
php { echo "Match found for joe!";
php { }
php { }
Match found for joe!
php >
Edit: We could also use file_get_contents()
instead of file()
, so we just get the file contents as a string, and convert it into an array ourselves: 编辑:我们也可以使用
file_get_contents()
而不是file()
,所以我们只将文件内容作为字符串获取,然后将其自己转换为数组:
$data = file_get_contents('test.txt');
foreach (explode("\n", $data) as $line) {
$row = explode(":", $line);
if ($row[0] == "joe" && $row[1] == "secret") {
echo "Match found for joe!";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.