鍍金池/ 問答/PHP  Linux/ PHP在某個文件的倒數(shù)第二行之后插入一行字符串

PHP在某個文件的倒數(shù)第二行之后插入一行字符串

本來想用PHP 執(zhí)行Linux sed插入文檔 簡單方便,但是目前php無權(quán)限執(zhí)行shell命令。

請問,用php代碼怎么實現(xiàn)該要求?

回答
編輯回答
伐木累
$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 順序應(yīng)該錯了,不過很好修改,就不修改源代碼了,還有一些校驗也沒做,主要就針對樓主需求做個簡單示例。關(guān)鍵函數(shù)是:fseek

2017年1月30日 06:23
編輯回答
涼心人
//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',"http://add text here\n".$need_add_text,$text);
file_put_contents('a.txt',$text_new);
2017年9月28日 16:19