通过查找特定字符串来编辑文件中的行



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

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

这是一个片段(由另一个论坛上的某人给出(:

<?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 呢?

您可以制作包含对 '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]]);
    }
}

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

而且,使用file和/或file_put_contents功能不需要fopen

$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));

最新更新