我有一个如下所示的ini文件
[PeopleA]
names=jack, tom, travis
color=red, blue, orange
[PeopleB]
names=sam, chris, kyle
color=purple, green, cyan
目标是提取特定值并使用PHP删除它
我的代码:
remove_ini($file, 'PeopleA', 'names', 'jack'); // call function
function remove_ini($file, $section, $key, $value) {
$config_data = parse_ini_file($file, true);
$raw_list = $config_data[$section][$key];
$list = explode(", ", $raw_list);
$index = array_search($value, $list);
unset($list[$index]); //remove from list
$config_data[$section][$key] = ''; // empty config_data
foreach($list as $list_item){ // re-iterate through and add to config_data w/o val passed in
if (empty($config_data[$section][$key])) {
$config_data[$section][$key] = $list_item;
} else {
$config_data[$section][$key] .= ', ' . $list_item;
}
}
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($file, $new_content);
}
似乎发生的事情是它在第一次执行时被删除,但是此后它开始被删除为剩余值。
我只是用remove_ini($file, 'PeopleA', 'names', 'jack');
调用该函数。
不知道发生了什么或为什么要删除的东西不止是名为“ jack”的东西,可以利用一些见解。谢谢!
答案 0 :(得分:1)
remove('file.ini', 'PeopleA', 'names', 'travis');
function remove($file, $section, $key, $value, $delimiter = ', ')
{
$ini = parse_ini_file($file, true);
if (!isset($ini[$section]) or !isset($ini[$section][$key]))
{
return false;
}
$values = explode($delimiter, $ini[$section][$key]);
$values = array_diff($values, [$value]);
$values = implode($delimiter, $values);
if ($values)
{
$ini[$section][$key] = $values;
}
else
{
unset($ini[$section][$key]);
}
$output = [];
foreach ($ini as $section => $values)
{
$output[] = "[$section]";
foreach ($values as $key => $val)
{
$output[] = "$key = $val";
}
}
$output = implode(PHP_EOL, $output);
return file_put_contents($file, $output);
}