PHP在某个文件的倒数第二行之后插入一行字符串

本来想用PHP 执行Linux sed插入文档 简单方便,但是目前php无权限执行shell命令。

请问,用php代码怎么实现该要求?

阅读 3.7k
2 个回答
//a.txt
aaa
bbb
//add text here
ccc
$need_add_text = '1111111xxxxxx';
$text = file_get_contents('a.txt');
$text_new = str_replace('//add text here',"//add text here\n".$need_add_text,$text);
file_put_contents('a.txt',$text_new);
$handle = fopen('log.txt', 'r+');
$i = -1;
$lastLine = '';

while(true){
    fseek($handle, $i, SEEK_END);
    $char = fgetc($handle);
   
    if($char == "\n"){
        fwrite($handle, "new line \n". $lastLine);
        exit();
    }else{
        $lastLine .= $char;
    }

    $i --;
}

编辑:$lastLine 顺序应该错了,不过很好修改,就不修改源代码了,还有一些校验也没做,主要就针对楼主需求做个简单示例。关键函数是:fseek

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题