【发布时间】: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 接入点)以及一些参数(例如“启用/禁用”)
-
那是值,但你知道参数的名称吗?
-
是的,我知道他们的名字