簡體   English   中英

修改PHP中文件的內容

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM