修改php中的文件内容

时间:2015-04-10 13:20:19

标签: 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

        }

如果文件已经存在,我需要从中读取QTY并进行更新。如果我知道之前的字符串,是否有一种快速简便的方法来获取它(即当前的QTY)

2 个答案:

答案 0 :(得分:0)

当您打开这样的文件时,您可以指定"或者死掉"像这样:

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

然后你可以写你喜欢的文件,然后关闭它。如果文件已经存在,它将只打开现有文件。如果它不存在,PHP将创建该文件。

答案 1 :(得分:0)

<?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

?>