简体   繁体   English

修改PHP中文件的内容

[英]Modify content of file in php

This file stores the number of item ordered to date. 该文件存储了迄今为止订购的商品数量。 Therefore, I will need to read from the file for current number ordered and add it to the current quantity ordered and write it back. 因此,我需要从文件中读取当前订购的数量,并将其添加到当前订购数量中,然后写回。

I am new to PHP, so I am not sure what is the best approach here. 我是PHP的新手,所以我不确定这里最好的方法是什么。

The format of the file is as follows: 该文件的格式如下:

        $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

        }

If the file already exists, I need to read the QTY from it and update it. 如果文件已经存在,我需要从中读取数量并进行更新。 Is there a quick and easy way to get it (ie, current QTY to date), provided that I know the string before it? 如果我知道之前的字符串,是否有一种快速简便的方法来获取它(即当前的当前数量)?

When you open a file like that you can specify "or die" like this: 当您打开这样的文件时,您可以像这样指定“或死”:

$filename = fopen("ordersToDate.txt", "w") or die ("Can't open file.");

Then you can write to the file like you're doing and then close it. 然后,您可以像执行操作一样写入文件,然后将其关闭。 If the file exists already it will just open the existing one. 如果该文件已经存在,它将打开现有的文件。 If it doesn't exist PHP will create the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM