[英]Modify content of file in php
该文件存储了迄今为止订购的商品数量。 因此,我需要从文件中读取当前订购的数量,并将其添加到当前订购数量中,然后写回。
我是PHP的新手,所以我不确定这里最好的方法是什么。
该文件的格式如下:
$filename = "ordersToDate.txt";
if (!file_exists($filename))
{
$file = fopen($filename, "w");
$toWrite = "Total quantity ordered to date
\r\nTotal number of apples: ".$appleQty.
"\r\nTotal number of oranges: ".$orangeQty.
"\r\nTotal number of bananas: ".$bananaQty;
fwrite($file, $toWrite);
fclose($file);
}
else
{
// read individual item QTY ordered to date, add it with current ordered QTY and write back
}
如果文件已经存在,我需要从中读取数量并进行更新。 如果我知道之前的字符串,是否有一种快速简便的方法来获取它(即当前的当前数量)?
当您打开这样的文件时,您可以像这样指定“或死”:
$filename = fopen("ordersToDate.txt", "w") or die ("Can't open file.");
然后,您可以像执行操作一样写入文件,然后将其关闭。 如果该文件已经存在,它将打开现有的文件。 如果不存在,PHP将创建该文件。
<?php
// can add another one for 'bananas: ' etc.
$re = "/(?!apples: )(\\d)/"; // for apples
// $str = file_get_contents($filename);
$str = "Total quantity ordered to date\r\nTotal number of apples: 3\r\nTotal number of oranges: 4\r\nTotal number of bananas: 3";
$subst = "5"; // $subst = $new_number;
// replace the number after 'apples: ' with whatever you want
$result = preg_replace($re, $subst, $str, 1);
echo var_dump($result);
// file contents, with apple number replaced with 5 (from 3) can now be written to file
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.