PHP文件操作之,插入某行,删除某行,获取行号

 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 $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     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值