文本文件(text.txt):
#Minecraft server properties
#Tue Sep 23 18:07:26 CEST 2014
generator-settings=
op-permission-level=4
allow-nether=true
level-name=world
enable-query=true
allow-flight=false
announce-player-achievements=true
server-port=25565
query.port=25565
level-type=DEFAULT
enable-rcon=false
force-gamemode=false
level-seed=
server-ip=
max-build-height=256
如何替换某些行的值,例如:
server-port=25565
替换为:
server-port=25585
但是没有找到' server-port = 25565'并替换为' server-port = 25585' 发现服务器端口所在的行和分配需要替换的值。
示例:
<?php
$myfile = fopen("text.txt", "r") or die("Unable to open file!");
...
fclose($myfile);
?>
编辑: 当找到这个并保存时替换文本文件。
答案 0 :(得分:2)
由于您的格式看起来像PHP配置文件(.ini)
,为什么不使用 parse_ini_file 函数?
$ini = parse_ini_file("text.txt");
echo "<pre>".print_r($ini,TRUE)."</pre>";
或
echo $ini["server-port"];
改变它:
$ini["server-port"] = 25585;
再次使用以下内容保存.txt文件:
$f = fopen("text.txt","w");
foreach($ini as $k=>$v) {
fwrite($f,$k."=".$v.PHP_EOL);
}
fclose($f);
您可能需要使用#
;
评论代码
<强>更新强>
$lines = file("text.txt",FILE_IGNORE_NEW_LINES);
// modify
foreach($lines as &$line) {
$val = explode("=",$line);
if ($val[0]=="server-port") {
$val[1] = "25585";
$line = implode("=",$val);
}
}
unset($line);
// save again
$f = fopen("text.txt","w");
foreach($lines as $line) {
fwrite($f,$line.PHP_EOL);
}
fclose($f);
答案 1 :(得分:1)
<?php
$file = "file.txt";
$content = file($file);
foreach ($content as $line_num => $line) {
if (false === (strpos($line, 'server-port=25565'))) continue;
$content[$line_num] = "server-port=25585\n";
}
file_put_contents($file, $content);
在
#Minecraft server properties #Tue Sep 23 18:07:26 CEST 2014 generator-settings= op-permission-level=4 allow-nether=true level-name=world enable-query=true allow-flight=false announce-player-achievements=true server-port=25565 query.port=25565 level-type=DEFAULT enable-rcon=false force-gamemode=false level-seed= server-ip= max-build-height=256
在
#Minecraft server properties #Tue Sep 23 18:07:26 CEST 2014 generator-settings= op-permission-level=4 allow-nether=true level-name=world enable-query=true allow-flight=false announce-player-achievements=true server-port=25585 query.port=25565 level-type=DEFAULT enable-rcon=false force-gamemode=false level-seed= server-ip= max-build-height=256
修改强>
您可以将$new_port
变量修改为您想要的任何内容。
$path = "file.txt";
$new_port = 25585;
$content = file($path);
foreach ($content as $line_num => $line) {
if (false === (strpos($line, 'server-port'))) continue;
$content[$line_num] = "server-port=$new_port\n";
}
file_put_contents($path, $content);