<?php// fedora-centos-apache-php-cannot-write-delete-file// getsebool -a|grep httpd// httpd_unified --> off// setsebool -P httpd_unified 1replaceTarget("test.txt", "aaaaaaaaaaaaaaaaa", "AAAAA");//unlink("test.txt");#替換指定字串function replaceTarget($filePath, $replaceCont, $target){ $result = null; $fileCont = file_get_contents($filePath); $targetIndex = strpos($fileCont, $target); #尋找目標字串的座標 if ($targetIndex !== false) { #找到target的前一個分行符號 $preChLineIndex = strrpos(substr($fileCont, 0, $targetIndex + 1), "\n"); #找到target的後一個分行符號 $AfterChLineIndex = strpos(substr($fileCont, $targetIndex), "\n") + $targetIndex; if ($preChLineIndex !== false && $AfterChLineIndex !== false) { #刪掉指定行,插入新內容 $result = substr($fileCont, 0, $preChLineIndex + 1) . $replaceCont . "\n" . substr($fileCont, $AfterChLineIndex + 1); file_put_contents($filePath, $result); //$fp = fopen($filePath, "w+"); //fwrite($fp, $result); //fclose($fp); } }}#在需要尋找的內容後一行新起一行插入內容function insertAfterTarget($filePath, $insertCont, $target){ $result = null; $fileCont = file_get_contents($filePath); $targetIndex = strpos($fileCont, $target); #尋找目標字串的座標 if ($targetIndex !== false) { #找到target的後一個分行符號 $chLineIndex = strpos(substr($fileCont, $targetIndex), "\n") + $targetIndex; if ($chLineIndex !== false) { #插入需要插入的內容 $result = substr($fileCont, 0, $chLineIndex + 1) . $insertCont . "\n" . substr($fileCont, $chLineIndex + 1); file_put_contents($filePath, $result); //$fp = fopen($filePath, "w+"); //fwrite($fp, $result); //fclose($fp); } }}#刪除內容所在的某一行function delTargetLine($filePath, $target){ $result = null; $fileCont = file_get_contents($filePath); $targetIndex = strpos($fileCont, $target); #尋找目標字串的座標 if ($targetIndex !== false) { #找到target的前一個分行符號 $preChLineIndex = strrpos(substr($fileCont, 0, $targetIndex + 1), "\n"); #找到target的後一個分行符號 $AfterChLineIndex = strpos(substr($fileCont, $targetIndex), "\n") + $targetIndex; if ($preChLineIndex !== false && $AfterChLineIndex !== false) { #重新寫入刪掉指定行後的內容 $result = substr($fileCont, 0, $preChLineIndex + 1) . substr($fileCont, $AfterChLineIndex + 1); file_put_contents($filePath, $result); //$fp = fopen($filePath, "w+"); //fwrite($fp, $result); //fclose($fp); } }}#擷取某段內容的行號/** * @param $filePath * @param $target 待尋找欄位 * @param bool $first 是否再匹配到第一個欄位後退出 * @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;}?>
referer: http://www.cnblogs.com/zemliu/archive/2012/06/16/2551541.html