推荐:《php视频教程》
php文件操作之,插入某行,删除某行,获取行号
#在需要查找的内容后一行新起一行插入内容 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); $fp = fopen($filepath, "w+"); fwrite($fp, $result); fclose($fp); } }19 } #删除内容所在的某一行 function deltargetline($filepath, $target) { $result = null;25 $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); $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; }
以上就是php如何删除某一行的详细内容。