PHP:在文件的特定行之间插入内容?

zf2sa74q  于 2023-10-15  发布在  PHP
关注(0)|答案(3)|浏览(105)

假设我有一个TXT文件(some.txt),其中包含以下内容:

data of first line
data of next line
#start-marker

data of next line
#end-marker
data of next line

我想在#start-marker后面写几行
目前,我有这个:

$fp = fopen('some.txt','r+');
$insertPos=0;
while (!feof($fp)) {
    $line=fgets($fp);
    if (strpos($line, '#start-marker')!==false) {
        $insertPos=ftell($fp);
}
fseek($fp,$insertPos);
fwrite($fp,'Data to be written');
fclose($fp);

但是,问题是:

data of first line
data of next line
#start-marker
Data to be written

所有行在新插入的行后消失。
如何做到这一点?
预期输出:

data of first line
data of next line
#start-marker

Data to be written
data of next line
#end-marker
data of next line
ztmd8pv5

ztmd8pv51#

$myfile = file_get_contents('some.txt');
$insert = '#start-marker blah blah blah new data here';
$myfile = str_replace('#start-marker', $insert, $myfile, 1);
file_put_contents('some.txt', $myfile);
oprakyz7

oprakyz72#

我想你是在找append to file。尝试将'r+'改为将模式a+添加到代码中:

$fp = fopen('some.txt','a+');
$insertPos=0;
while (!feof($fp)) {
    $line=fgets($fp);
    if (strpos($line, '#start-marker')!==false) {
        $insertPos=ftell($fp);
}
fseek($fp,$insertPos);
fwrite($fp,'Data to be written');
fclose($fp);

参考:模式参数-http://php.net/manual/en/function.fopen.php

hmmo2u0o

hmmo2u0o3#

寻找js代码注入到文件使用php检查下面的代码使用js文件或文件路径追加代码

<?php 
$jsFile = '';
 $fileLines = file($jsFile);

$Line1 = 10; 
$Line2 = 20;
$Code1 = "js code for line 10";
$Code2 = "js code for line 20";
array_splice($fileLines, $Line1 - 1, 0, $Code1);
array_splice($fileLines, $Line2 - 1, 0, $Code2);

file_put_contents($jsFile, implode('', $fileLines));
?>

相关问题