PHP檔案操作之,插入某行,刪除某行,擷取行號

來源:互聯網
上載者:User
 1 #在需要尋找的內容後一行新起一行插入內容 2     function insertAfterTarget($filePath, $insertCont, $target) 3     { 4         $result = null; 5         $fileCont = file_get_contents($filePath); 6         $targetIndex = strpos($fileCont, $target); #尋找目標字串的座標 7  8         if ($targetIndex !== false) { 9             #找到target的後一個分行符號10             $chLineIndex = strpos(substr($fileCont, $targetIndex), "\n") + $targetIndex;11             if ($chLineIndex !== false) {12                 #插入需要插入的內容13                 $result = substr($fileCont, 0, $chLineIndex + 1) . $insertCont . "\n" . substr($fileCont, $chLineIndex + 1);14                 $fp = fopen($filePath, "w+");15                 fwrite($fp, $result);16                 fclose($fp);17             }18         }19     }20 21     #刪除內容所在的某一行22     function delTargetLine($filePath, $target)23     {24         $result = null;25         $fileCont = file_get_contents($filePath);26         $targetIndex = strpos($fileCont, $target); #尋找目標字串的座標27 28         if ($targetIndex !== false) {29             #找到target的前一個分行符號30             $preChLineIndex = strrpos(substr($fileCont, 0, $targetIndex + 1), "\n");31             #找到target的後一個分行符號32             $AfterChLineIndex = strpos(substr($fileCont, $targetIndex), "\n") + $targetIndex;33             if ($preChLineIndex !== false && $AfterChLineIndex !== false) {34                 #重新寫入刪掉指定行後的內容35                 $result = substr($fileCont, 0, $preChLineIndex + 1) . substr($fileCont, $AfterChLineIndex + 1);36                 $fp = fopen($filePath, "w+");37                 fwrite($fp, $result);38                 fclose($fp);39             }40         }41     }42 43     #擷取某段內容的行號44     /**45      * @param $filePath46      * @param $target   待尋找欄位47      * @param bool $first   是否再匹配到第一個欄位後退出48      * @return array49      */50     function getLineNum($filePath, $target, $first = false)51     {52         $fp = fopen($filePath, "r");53         $lineNumArr = array();54         $lineNum = 0;55         while (!feof($fp)) {56             $lineNum++;57             $lineCont = fgets($fp);58             if (strstr($lineCont, $target)) {59                 if($first) {60                     return $lineNum;61                 } else {62                     $lineNumArr[] = $lineNum;63                 }64             }65         }66         return $lineNumArr;67     }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.