我能够使用下面的代码来做到这一点。该代码使用 PHP CLI 接受参数并使用这些值创建一个新文件。
$file = file('named.conf');
$arg = getopt("", array('zone:', 'type:', 'file:'));
$internal_end = 0;
$external_end = 0;
$flag = false;
$count = 0;
foreach ($file as $index => $line) {
if (preg_match('/view\s*"internal"\s*{/i', $line) !== 1 && !$flag) {
continue;
}
$flag = true;
$ob = substr_count($line, '{');
$count += $ob;
$cb = substr_count($line, '}');
$count -= $cb;
if ($count == 0) {
$internal_end = $index;
break;
}
}
array_splice($file, $internal_end, 0, array(
"\n",
"zone \"".$arg['zone']."\" {\n",
"\ttype ".$arg['type'].";\n",
"\tfile \"".$arg['file']."\";\n",
"};\n",
"\n"
));
$flag = false;
$count = 0;
foreach ($file as $index => $line) {
if (preg_match('/view\s*"external"\s*{/i', $line) !== 1 && !$flag) {
continue;
}
$flag = true;
$ob = substr_count($line, '{');
$count += $ob;
$cb = substr_count($line, '}');
$count -= $cb;
if ($count == 0) {
$external_end = $index;
break;
}
}
array_splice($file, $external_end, 0, array(
"\n",
"zone \"".$arg['zone']."\" {\n",
"\ttype ".$arg['type'].";\n",
"\tfile \"".$arg['file']."\";\n",
"};\n",
"\n"
));
file_put_contents('named_new.conf', implode('', $file));
执行代码调用php script.php --zone=my.new.external.zone --type=master --file=my.new.external.zone.db