PHPファイル操作の場合、ある行を挿入し、ある行を削除し、行番号を取得する

12397 ワード

 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), "
") + $targetIndex; 11 if ($chLineIndex !== false) { 12 # 13 $result = substr($fileCont, 0, $chLineIndex + 1) . $insertCont . "
" . 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), "
"); 31 # target 32 $AfterChLineIndex = strpos(substr($fileCont, $targetIndex), "
") + $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 $filePath 46 * @param $target 47 * @param bool $first 48 * @return array 49 */ 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 }