【问题标题】:Edit lines in a file by looking for a specific string?通过查找特定字符串来编辑文件中的行?
【发布时间】:2019-02-05 09:28:08
【问题描述】:

我需要编辑文件中的某些特定行,但是由于此文件是配置文件(用于 Wi-Fi 接入点),因此它的某些行有时会自行编辑/删除/添加。

所以我想知道是否可以先查找特定字符串,然后对其进行编辑。

这是一个sn-p(由另一个论坛上的某人提供):

<?php

// Function that replaces lines in a file
function remplace(&$printArray,$newValue) {
  $ligne    = explode('=',$printArray);
  $ligne[1] = $nouvelleValeur;
  $printArray = implode('=',$line); 
}
// Read the file then put it in an array
$handle=fopen("file.cfg","r+");
$array = file('file.cfg',FILE_IGNORE_NEW_LINES);

// Displaying it to see what is happening
foreach($array as $value) {
 print "$value<br/>";
}
// Replace line 38 
remplace($array[37],'replacement text');
// Replace line 44
remplace($array[43],'replacement text');

// Edit then saves the file
file_put_contents('file.cfg', implode(PHP_EOL,$array));
fclose($handle);

?>

此代码编辑行由 $array[] 显示,但正如我之前提到的,行确实在移动,因此我需要查找特定的字符串,而不是仅仅选择可能是错误的行。

那么 substr_replace、strpbrk 和/或 strtr 呢?

【问题讨论】:

  • 您对要更新的文本了解多少 - 确切值、模式...?
  • 使用preg_grep找到他们php.net/manual/en/function.preg-grep.php
  • 要更新的文本必须是随机生成的 SSID 和密码(用于 Wi-Fi 接入点)以及一些参数(例如“启用/禁用”)
  • 那是值,但你知道参数的名称吗?
  • 是的,我知道他们的名字

标签: php arrays string


【解决方案1】:

您可以制作包含对 'key'=>'new_value' 的替换数组

$replacement = [
  'password' => 'new_pass',
  'SSID' => 'newSSID'
];

然后检查配置数组的当前行是否以该数组的键开头。如果是,请更换它。

foreach($array as &$value) {
    if(preg_match('/^(\w+)\s*=/', $value, $m) and 
       isset($replacement[$m[1]])) {
           remplace($value, $replacement[$m[1]]);
    }
}

【讨论】:

    【解决方案2】:

    您可以逐行搜索要替换的字符串。这只是一种方法,非常基本,因为您似乎对此很陌生。您甚至可以使用 match 函数或其他方法。有很多方法...

    而且你不需要fopen 来使用file 和/或file_put_contents 函数。

    $lines = file('file.cfg', FILE_IGNORE_NEW_LINES);
    
    foreach ($lines as &$line) {
      $ligne = explode('=', $line);
    
      if ($ligne[1] === 'str to serach for') {
        $ligne[1] = 'replacement text';
        $line = implode('=', $ligne); 
      }
    }
    
    file_put_contents('file.cfg', implode(PHP_EOL, $lines));
    

    【讨论】:

      猜你喜欢
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2014-04-23
      相关资源
      最近更新 更多