更新文件中的字符串


Update string in file

我有一个文件,里面有这样的信息:

    IP=121.0.0.1 Status=On Name=Name  
    IP=121.0.0.1 Status=On Name=Name 
    IP=121.0.0.1 Status=On Name=Name  
    IP=121.0.0.1 Status=On Name=Name  
    IP=127.0.0.1 Status=On Name=Name 
    IP=121.0.0.1 Status=On Name=Name  
    IP=121.0.0.1 Status=On Name=Name 
    IP=121.0.0.1 Status=On Name=Name

如何更新此文件中的信息?例如,如果localhost IP将Status设置为Off,将Name设置为test等,我将如何更新该行。我尝试通过IP地址(在本例中为localhost-127.0.0.1)定位我要修改的行,然后用str_replace()等将Status=的值替换为Off。但当我再次尝试将其更改回On时,它会在另一行上写入/空行/添加更多信息。

我尝试过的代码:

<?php
$file = fopen('user_info.wrd','r+');
while (!feof($file))
 {
  $str=fgets($file);
  if (strstr($str,$_SERVER['REMOTE_ADDR'])) 
    {
     $Status=substr($str,strpos($str,'Status=')+7);
     $Status=substr($Status,0,strpos($Status,' '));
     fseek($file,(ftell($file)-strlen($str)));
     $str=str_replace($Status,'Off',$str);
     echo $str;
     $str=trim($str);
     fwrite($file,$str);
     fclose($file);
     die;
    }
 }  
?>

以下是我的read_file和write_file函数版本(代码没有经过测试,但应该可以工作)。

function read_file($filename) {
  $contents = file_get_contents($filename);
  $lines = explode((strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? "'r'n" : "'n"), $contents);
  $data = array();
  foreach($lines as $line) {
    $fields = explode(" ", $line);
    $ip_address = null;
    foreach($fields as $field) {
      $keyvaluepair = explode('=', $field);
      if ($keyvaluepair[0] === 'IP') {
        $ip_address = $keyvaluepair[1];
        $data[$ip_address] = array();
      } else {
        $data[$ip_address][$keyvaluepair[0]] = $keyvaluepair[1];
      }
    }
  }
  return $data;
}
function write_file($filename, $array) {
  $data = '';
  foreach($array as $ip_address => $flags) {
    $data .= "IP={$ip_address} Status={$flags['Status']} Name={$flags['Name']}";
    $data .= (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? "'r'n" : "'n");
  }
  file_put_contents($filename, $data);
}

用法:

$data = read_file('filename');
$data['127.0.0.1']['Status'] = 'Off';
$data['127.0.0.1']['Name'] = 'My_Fancy_Name'; // note that spaces in the name are not allowed!
write_file('filename', $data);