【问题标题】:Replace a certain line or word using php使用 php 替换特定的行或单词
【发布时间】:2020-09-14 08:38:37
【问题描述】:

有谁知道如何使用下面的 php 示例文件名替换文件特定行中的特定行或单词或数字

server.cfg

game dm
plugins etc etc etc
ports 2345

那么 php 可以只更新端口号吗?使用任何形式或东西?会有帮助的

【问题讨论】:

标签: php numbers filenames word


【解决方案1】:

以下是分步解决方案,每行都有说明。

注意:server.cfg 必须是 PHP 可写的。确保设置权限,以便 PHP 可以首先写入该文件。否则,您将收到“无法打开流:权限被拒绝”错误。

// Define the path to the file here
$myFile = '/path/to/server.cfg';

// Define the new port number here
$newPort = '12345';
$newGameMode = 'cool';
$newMaxPlayers = 120;

// Load the file
$contents = file_get_contents($myFile);

// Modify the contents
$contents = preg_replace('/(ports) (\d+)/', '$1 '.$newPort, $contents);
$contents = preg_replace('/(gamemode) ([a-z]+)/', '$1 '.$newGameMode, $contents);
$contents = preg_replace('/(maxplayers) (\d+)/', '$1 '.$newMaxPlayers, $contents);

// Overwrite the file with the new contents
file_put_contents($myFile, $contents);

【讨论】:

    【解决方案2】:

    很好,但我怎么能用多行示例来做到这一点

    $newport = $_POST['ports'];
    $newgamemode = $_POST['gamemode'];
    $newmaxplayers = $_POST['maxplayers'];
    $contents = file_get_contents($myFile);
    $contents = preg_replace('/(ports) (\\d+)/', '$1 '.$newport, $contents);
    $contents = preg_replace('/(gamemode) (\\d+)/', '$1 '.$newgamemode, $contents);
    $contents = preg_replace('/(maxplayers) (\\d+)/', '$1 '.$newmaxplayers, $contents);
    file_put_contents($myFile, $contents);```
    
    the current cfg file looks like this 
    gamemode asdsad
    plugins discord04rel64 announce04rel64 
    ports 100
    sqgamemode scripts/main.nut
    maxplayers 100
    

    【讨论】:

    • 你在那里的东西看起来应该可以工作。它不工作吗?不过请注意 - 如果该配置文件实际上被某些软件服务使用,那么您的提议是非常危险的,因为您网站上的用户将能够轻松地利用它并将他们自己的配置注入该文件并可能接管您的网络服务器。
    • 不,不用担心安全性,只是代码确实起作用了只有 maxplayer 正在改变的部分,而不是其他变量
    • 顺便说一下,正则表达式中的 \d+ 只匹配数字。我看到您正在尝试匹配游戏模式中的字母。如果要匹配小写字母,请使用 [a-z]+
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多