从php中删除文件中的特殊行

时间:2014-07-15 12:05:53

标签: php

我有如下的php脚本,它是为了修改interfaces.conf文件内部而创建的。当eth0接口是dhcp时,我需要使其静态并为ip地址网关和子网掩码创建额外的三行。当eth0是静态的时,我需要将其更改为dhcp,但是我无法删除之前为上面的ip地址,网关和子网掩码创建的下三行。你能帮我解决这个问题吗?

<?php
$my_file = fopen("interfaces.conf","r") or die (" Unable to open file !");
$new_file = fopen("interfaces.txt","w") or die (" Unable to open file !");
$replaced = false;
while (!feof($my_file)){
    $line = fgets($my_file);
    if (stristr($line,'iface eth0 inet dhcp')) {
         $line = "iface eth0 inet static\n"."address"." "."192.168.42.1\n"."netmask"." "."255.255.255.0\n"."gateway"." "."192.168.42.0\n";
         $replaced = true;
    }
    elseif (stristr($line,'iface eth0 inet static')) {
         $line = "iface eth0 inet dhcp\n";
         $replaced = true;
    }
    fputs($new_file, $line);
}

fclose($my_file);
fclose($new_file);
if ($replaced){
    rename("interfaces.txt","interfaces.conf");
    }
else {
    unlink("interfaces.txt");
    }
?>

1 个答案:

答案 0 :(得分:-1)

脚本的实际结果是什么?你所做的事情看起来并不错。

编辑1:

快速解决方案是添加一个“注释行”(或知道以下行)以检测哪些行“跳过”以及何时重新启动将它们推送到新文件。

其他解决方案:我想你要删除的行有一个非常具体的“格式”。您可以使用正则表达式来查找/替换行;)

编辑2:

一种解决方案可能是这样的:

<?php
$my_file = fopen("interfaces.conf","r") or die (" Unable to open file !");
$new_file = fopen("interfaces.txt","w") or die (" Unable to open file !");
$replaced = false;
$lock = 0;
while (!feof($my_file)){
    $line = fgets($my_file);
    if (stristr($line,'iface eth0 inet dhcp')) {
        $line = "iface eth0 inet static\n"."address"." "."192.168.42.1\n"."netmask"."   "."255.255.255.0\n"."gateway"." "."192.168.42.0\n";
        $replaced = true;
    } elseif (stristr($line,'iface eth0 inet static')) {
        $line = "iface eth0 inet dhcp\n";
        fputs($new_file, $line); // replace this line 
        $lock = 3; // and lock the next 3 lines from being copied to the new file
        $replaced = true;
    }
    if($lock != 0) {
      $lock--;
    } else {
      fputs($new_file, $line);
    }
}

fclose($my_file);
fclose($new_file);
if ($replaced){
    rename("interfaces.txt","interfaces.conf");
}
else {
unlink("interfaces.txt");
}
?>