2 回答

TA貢獻1824條經驗 獲得超5個贊
問題是您只是將顏色文本替換為中的值
$file_contents = str_replace($colour, $value, $file_contents);
但這并不能取代整行。
使用preg_replace()
,您可以替換以顏色開頭的內容,然后=
將其替換為...
$file_contents = preg_replace("/{$colour}=.*/", "{$colour}={$value}", $file_contents);

TA貢獻1859條經驗 獲得超6個贊
發生這種情況是因為您的代碼僅用指定的值替換顏色。為此,您必須逐行加載文件,按 = 分解以分別獲得顏色和值,然后再次調整和存儲?;蛘呤褂谜齽t表達式。
我想提出不同的方法。而不是對作為字符串加載的文件進行操作,而是將文件作為數組加載。有一個函數可以實現此目的:parse_ini_file。
<?php
// load the file to array with elements key => value
$data = parse_ini_file('conf.txt');
var_dump($data);
// change the data in array however you want - here i add 1 to red everytime this script is called, but it can be whatever: $data['red'] = 2; or similar
$data['red']++;
// now just build the contents of the file again and save it
$contents = '';
foreach ($data as $key => $value) {
$contents .= $key.'='.$value.PHP_EOL;
}
file_put_contents('conf.txt', $contents);
結果:
// this is how the file looks like at start
cat conf.txt
red=0
green=23
blue=1
yellow=44
// this is how $data looks
array(4) {
["red"]=>
string(1) "0"
["green"]=>
string(2) "23"
["blue"]=>
string(1) "1"
["yellow"]=>
string(2) "44"
}
// and the file after the execution
cat conf.txt
red=1
green=23
blue=1
yellow=44
更改$data['red']++;為$data[$color] = $value;將其放入函數中即可。
- 2 回答
- 0 關注
- 153 瀏覽
添加回答
舉報