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

时间:2019-02-05 09:28:08

标签: php arrays string

我需要编辑文件中的某些特定行,但是,由于此文件是配置文件(用于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呢?

2 个答案:

答案 0 :(得分: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]]);
    }
}

答案 1 :(得分:0)

您可以搜索要逐行替换的字符串。这只是一种方法,非常基本,因为您似乎对此并不陌生。您甚至可以使用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));
相关问题