【问题标题】:Search a file for a string and replace everything after a character in that line在文件中搜索字符串并替换该行中字符之后的所有内容
【发布时间】:2020-11-11 03:32:31
【问题描述】:

我希望使用 PHP 打开一个文件(参见下面的示例),逐行搜索字符串 $colour 并将 "=" 之后的所有内容替换为 $value

file.txt 之前:

red=0
green=23
blue=999
yellow=44

如果我的$value"1" 并且我的颜色是"blue",我的文件应该更改为:

red=0
green=23
blue=1
yellow=44

到目前为止我的代码是:

function write($colour, $value) {
    $file = 'path';
    $file_contents = file_get_contents($file);
    $file_contents = str_replace($colour, $value, $file_contents);
    file_put_contents($file, $file_contents);
}

但是,这只是将$colour 替换为$value(不是“=”之后的所有内容)见下面我的输出:

red=0
green=23
1=999
yellow=44

我该怎么做?谢谢!

【问题讨论】:

    标签: php file file-handling write


    【解决方案1】:

    问题是您只是将颜色的文本替换为中的值

    $file_contents = str_replace($colour, $value, $file_contents);
    

    但这并不能取代整行。

    使用preg_replace(),您可以替换以颜色开头的内容,然后是=,直到行尾...

    $file_contents = preg_replace("/{$colour}=.*/", "{$colour}={$value}", $file_contents);
    

    【讨论】:

      【解决方案2】:

      发生这种情况是因为您的代码仅将颜色替换为指定的值。为此,您必须逐行加载文件,按 = 分解以分别具有颜色和值,然后再次调整和存储。或者使用正则表达式。

      我想提出不同的方法。而不是对作为字符串加载的文件进行操作,而是将文件作为数组加载。为此有一个函数:parse_ini_file。

      <?php
      
      // load the file to array with elements key => value
      $data = parse_ini_file('conf.txt');
      
      var_dump($data);
      
      // change the data in array however you want - here i add 1 to red everytime this script is called, but it can be whatever: $data['red'] = 2; or similar
      $data['red']++;
      
      // now just build the contents of the file again and save it
      $contents = '';
      foreach ($data as $key => $value) {
        $contents .= $key.'='.$value.PHP_EOL;
      }
      
      file_put_contents('conf.txt', $contents);
      

      结果:

      // this is how the file looks like at start
      cat conf.txt 
      red=0
      green=23
      blue=1
      yellow=44
      
      // this is how $data looks
      array(4) {
        ["red"]=>
        string(1) "0"
        ["green"]=>
        string(2) "23"
        ["blue"]=>
        string(1) "1"
        ["yellow"]=>
        string(2) "44"
      }
      
      // and the file after the execution
      cat conf.txt 
      red=1
      green=23
      blue=1
      yellow=44
      

      $data['red']++; 更改为$data[$color] = $value; 将其放入函数中即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-16
        • 1970-01-01
        • 2022-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-06
        相关资源
        最近更新 更多