fopen复制了同一行



我有一个像这样的文件:

1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]||55.183.567 

我创建了一个函数,在执行时添加给定的数字或删除已经存在的数字,在本例中为$added并等于100。这是我的代码:

$added = $_GET['added']; //100 for this example
$f = fopen($file, "w");
$list = file($file);
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~b$details[0]b~", 3)) {
foreach ($details as $key => $value) {
if ($key == 5) {
$newline .= str_replace("[" . $added . "]", "", $value);
} else {
$newline .= $value . "||";
}
}
$line = $newline . "n";
}
fputs($f, $line);
}
fclose($f);
}

这段代码应该从Rocky行中删除[100],因为它已经存在了。但是,在进一步执行时,它没有将其添加回去,而是复制了Rocky行并将其弄乱,因此文件看起来像这样:

1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]55.183.567
3||Rocky||21||male||USA||[100][200]55.183.567 
||
||

它为什么这样做?我看不懂……

谢谢。

首先,您应该在打开文件进行输出之前读取该文件,因为使用w模式打开会截断该文件。

第二,如果您只想更改其中一个字段,则不需要遍历$details中的字段。通过索引访问并赋值。

然后你可以用implode()把这行放回一起。

$list = file($file);
$f = fopen($file, "w");
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~b$details[0]b~", 3)) {
if (strpos("[$added]", $details[5]) === false) {
$details[5] = "[$added]" . $details[5];
} else {
$details[5] = str_replace("[$added]", "", $details[5]);
}
$line = implode('||', $details)
}
fputs($f, $line);
}
fclose($f);

最新更新