簡體   English   中英

通過查找特定字符串來編輯文件中的行?

[英]Edit lines in a file by looking for a specific 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 呢?

您可以制作包含 'key'=>'new_value' 對的替換數組

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

然后檢查 config 數組的當前行是否以該數組的鍵開頭。 如果是,請更換它。

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

您可以逐行搜索要替換的字符串。 這只是一種方法,非常基本,因為您似乎對此不熟悉。 您甚至可以使用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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM