用php替换某一行或某一字

问题描述 投票:-1回答:1

有谁知道如何能用php文件名替换文件中的某一行或某一字或某一数字?

服务器.cfg

game dm
plugins etc etc etc
ports 2345

所以,php能不能更新端口号,用什么表格之类的?

php numbers filenames word
1个回答
0
投票

甜蜜的,但我怎么能做到这一点与多行的例子。

$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

0
投票

以下是一步一步的解决方法,包括每一行的解释。

注意:server.cfg必须是PHP可以写入的。 确保设置权限,使PHP可以先写入该文件。 否则你会得到一个 "failed to open stream. Permission denied "的错误。Permission denied "错误。

// 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);
© www.soinside.com 2019 - 2024. All rights reserved.