使用fopen在出现多次文本后添加一些文本

问题描述 投票:-1回答:1

我想做的是用脚本为我的世界日历创建一个安装程序。我需要对主脚本中的文件之一进行一些更改。我已经设法使用上面的代码进行所需的更改。问题是不止一次发生。每当字符串重复时,如何进行相同的更改。它可能发生0或1或2次

$target_line='$second = (int)substr($raw_date, 17, 2);';
$lines_to_add= '$raw_date =  translate_from_gregorian($raw_date);'. PHP_EOL.
    '$year = (int)substr($raw_date, 0, 4);'. PHP_EOL.
    '$month = (int)substr($raw_date, 5, 2);'. PHP_EOL.
    '$day = (int)substr($raw_date, 8, 2);'. PHP_EOL;
$config ='includes/functions/general.php';
$file=fopen($config,"r+") or exit("Unable to open file!");
$insertPos=0;  // variable for saving //Users position
 while (!feof($file)) {
    $line=fgets($file);
    if (strpos($line,$target_line)!==false) { 
        $insertPos=ftell($file);    // ftell will tell the position where the pointer moved, here is the new line after //Users.
        $newline =  $lines_to_add;
    } else {
        $newline.=$line;   // append existing data with new data of user
    }
}

fseek($file,$insertPos);   // move pointer to the file position where we saved above 
fwrite($file, $newline);

fclose($file);
php fopen fwrite
1个回答
0
投票

将整个文件读入变量。用str_replace()进行所有替换。然后将结果写回到文件中。

$contents = file_get_contents($config);
$contents = str_replace($target_line, $target_line . PHP_EOL . $lines_to_add);
file_put_contents($config, $contents);
© www.soinside.com 2019 - 2024. All rights reserved.