PHP 刪除文字檔的任意一行或添加…____PHP

來源:互聯網
上載者:User
PHP 刪除文字檔的任意一行或添加一行 刪除現實存在的文字檔的指定行,這一行可以是任意的,即由使用者決定。刪除文字檔的任意一行非常有意義,比如,我們用一個文字檔記錄註冊使用者的相關資訊(每一行一條資訊),現在我們需要刪除其中的某一條。
<? php
$filename = " aaa.txt " ; // 定義操作檔案
$delline = 3 ;  // 要刪除的行數
$farray = file ( $filename ); // 讀取檔案資料到數組中
for ( $i = 0 ; $i < count ( $farray ); $i ++ )
{   
     if ( strcmp ( $i + 1 , $delline ) == 0 )   // 判斷刪除的行,strcmp是比較兩個數大小的函數
    {   
         continue ;
    }   
     if ( trim ( $farray [ $i ]) <> "" )   // 刪除檔案中的所有空行
    {   
         $newfp .= $farray [ $i ];     // 重新整理後的資料
    }   
}   
$fp = @ fopen ( $filename , " w " ); // 以寫的方式開啟檔案
@ fputs ( $fp , $newfp );
@ fclose ( $fp );
?>
文字檔aaa.txt如下:
10.8.0.1:255.255.255.0
10.8.0.2:255.255.255.0
10.8.0.3:255.255.255.0
10.8.0.4:255.255.255.0
10.8.0.5:255.255.255.0
10.8.0.6:255.255.255.0
10.8.0.8:255.255.255.0

添加一行資料到最後一行
<? php
$filename = " aaa.txt " ; // 定義操作檔案
$fcontent   =   file ( $filename );  // file()把整個檔案讀入一個數組中
$fp    =   fopen ( " $filename " , " a " );
$str   =   " 10.8.0.9:255.255.255.0\n " ;
fwrite ( $fp ,   $str );
?>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.