dqhsv0147421 2014-09-23 17:01
浏览 35
已采纳

如何从文本文件中更改一行(PHP)

Text file(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

How to replace the value of some line, such as these:

server-port=25565

Replace with:

server-port=25585

But no to find 'server-port=25565' and replace with 'server-port=25585' It is found that the lines in which the server port and to allocate a value that needs to be replaced.

Example:

<?php
    $myfile = fopen("text.txt", "r") or die("Unable to open file!");
    ...
    fclose($myfile);
?>

EDIT: And when finded this and saved replace the text file.

  • 写回答

2条回答 默认 最新

  • dongxiang5879 2014-09-23 17:17
    关注

    Since your format looks suspiciously like a PHP configuration file (.ini), why not using the parse_ini_file function?

    $ini = parse_ini_file("text.txt");
    echo "<pre>".print_r($ini,TRUE)."</pre>";
    

    or

    echo $ini["server-port"];
    

    Change it:

    $ini["server-port"] = 25585;
    

    Save again your .txt file with:

    $f = fopen("text.txt","w");
    foreach($ini as $k=>$v) {
       fwrite($f,$k."=".$v.PHP_EOL);
    }
    fclose($f);
    

    You may need to change your # comments symbol though with ;

    UPDATE

    $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条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题