Замените определенную строку или слово, используя php - PullRequest
0 голосов
/ 27 мая 2020

знает ли кто-нибудь, как можно заменить определенную строку, слово или число в определенной c строке файла, используя php пример имени файла ниже

server.cfg

game dm
plugins etc etc etc
ports 2345

так может php просто обновить номер порта? используя любую форму или что-то в этом роде? было бы полезно

Ответы [ 2 ]

0 голосов
/ 27 мая 2020

сладко, но как я могу это сделать с помощью примера с несколькими строками

$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 голосов
/ 27 мая 2020

Ниже приводится пошаговое решение с пояснениями для каждой строки.

ПРИМЕЧАНИЕ: 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);
...