简体   繁体   中英

Edit lines in a file by looking for a specific string?

I need to edit some specific lines in a file, however since this file is a configuration file (for a Wi-Fi Access Point), some of its lines sometimes edit/remove/add themselves.

So I wanted to know if it was possible to firstly look for a specific string, and then edit it.

Here is a snippet (given by somebody on another forum) :

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

?>

This code edit lines showed by $array[] but as I mentioned before, lines are literally moving so I need to look for the specific string(s) instead of just picking a line that could be the wrong one.

So what about substr_replace, strpbrk and/or strtr?

You can make such replacement array containing pairs 'key'=>'new_value'

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

Then check that the current line of the config array begins with the key of that array. If so, replace it.

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

You could search for the string you want to replace line by line. This is just one approach, very basic because you seems to be new to this. You could even go with match functions or else. There are many ways ...

And you don't need fopen for using file and/or file_put_contents function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM