这是我的代码:PHP读取.txt文件和编辑一行
$string2 = file_get_contents('maps/' . $region . '.txt');
$string2 = explode("\n", $string2);
foreach($string2 as $value2) {
$string2 = unserialize($value2);
if($string2['x_pos'] == ($x2 + 4) && $string2['y_pos'] == ($y2 + 8)) {
$length2 = strlen($string2['amount']);
$new_amount = ($string2['amount'] + 0) - ($resource_quantity + 0);
$changed = substr_replace($value2, $new_amount, 123, $length2);
file_put_contents('maps/' . $region . '.txt', $changed);
break 1;
}
}
我想要什么的代码做的是打开文件,读取每一行,直到它找到它想要的线和然后用编辑后的行重新保存该文件。问题是,它的工作原理,但它只保存与编辑的行,并摆脱所有其他行。
我想保持使用的方法(file_get_contents & file_put_contents)真的,除非有一个非常简单的方法来做到这一点。有人可以帮忙吗?我一直在寻找一段时间,找不到我在找什么。
使用['文件()'](http://php.net/file)功能,以及一些更明智的变量名。 – mario