php刪除某一行的實(shí)現(xiàn)方法:首先創(chuàng)建一個(gè)PHP示例文件;然后定義一個(gè)delTargetLine方法;接著通過strpos函數(shù)查找目標(biāo)字符串的坐標(biāo);最后刪除內(nèi)容所在的某一行即可。
推薦:《PHP視頻教程》
PHP文件操作之,插入某行,刪除某行,獲取行號
#在需要查找的內(nèi)容后一行新起一行插入內(nèi)容 function insertAfterTarget($filePath, $insertCont, $target) { $result = null; $fileCont = file_get_contents($filePath); $targetIndex = strpos($fileCont, $target); #查找目標(biāo)字符串的坐標(biāo) if ($targetIndex !== false) { #找到target的后一個(gè)換行符 $chLineIndex = strpos(substr($fileCont, $targetIndex), "n") + $targetIndex; if ($chLineIndex !== false) { #插入需要插入的內(nèi)容 $result = substr($fileCont, 0, $chLineIndex + 1) . $insertCont . "n" . substr($fileCont, $chLineIndex + 1); $fp = fopen($filePath, "w+"); fwrite($fp, $result); fclose($fp); } } 19 } #刪除內(nèi)容所在的某一行 function delTargetLine($filePath, $target) { $result = null; 25 $fileCont = file_get_contents($filePath); $targetIndex = strpos($fileCont, $target); #查找目標(biāo)字符串的坐標(biāo) if ($targetIndex !== false) { #找到target的前一個(gè)換行符 $preChLineIndex = strrpos(substr($fileCont, 0, $targetIndex + 1), "n"); #找到target的后一個(gè)換行符 $AfterChLineIndex = strpos(substr($fileCont, $targetIndex), "n") + $targetIndex; if ($preChLineIndex !== false && $AfterChLineIndex !== false) { #重新寫入刪掉指定行后的內(nèi)容 $result = substr($fileCont, 0, $preChLineIndex + 1) . substr($fileCont, $AfterChLineIndex + 1); $fp = fopen($filePath, "w+"); fwrite($fp, $result); fclose($fp); } } } #獲取某段內(nèi)容的行號 /** * @param $filePath * @param $target 待查找字段 * @param bool $first 是否再匹配到第一個(gè)字段后退出 * @return array */ function getLineNum($filePath, $target, $first = false) { $fp = fopen($filePath, "r"); $lineNumArr = array(); $lineNum = 0; while (!feof($fp)) { $lineNum++; $lineCont = fgets($fp); if (strstr($lineCont, $target)) { if($first) { return $lineNum; } else { $lineNumArr[] = $lineNum; } } } return $lineNumArr; }