2010-07-07 49 views
2

我有兩個配置文件。一個是ini one is php。他們看起來像下面。我需要更新數據庫文件名但其餘的文件必須是不變。任何想法如何做?閱讀,編輯和保存配置文件(php)

的config.ini

; Turning Debugging on 
[test] 
developer = true 

; Production site configuration data 
[production] 
database.params.dbname = /var/lib/firebird/data/radek_db.gdb 

和setting.php

<?php 
/** 
The settings file 
*/ 

#This will be done automatically if u want to override it uncomment the next line few lines 
/* 
    $Path = 'mainline'; 

#Database to connect to: 
    $Database  =  "radek_db"; 
?> 

回答

3

你可以用file_get_contents()把文件讀到一個字符串上,對它做一個str_replace()或preg_replace(),然後用file_put_contents()保存它。

我會聯繫那些所有的文件,但我沒有信譽,使多個鏈接...

編輯:如果你所知道的是選項的名稱,您可以使用preg_match通過正則表達式(類似於'/^database\.params\.dbname = (.*)$/')查找選項名稱,然後對您找到的名稱執行str_replace。

事情是這樣的:

$file = file_get_contents('/path/to/config/file'); 
$matches = array(); 
preg_match('/^database\.params\.dbname = (.*)$/', $file, $matches); 
$file = str_replace($matches[1], $new_value, $file); 
file_put_contents('/path/to/config/file', $file); 
+0

多於字符串替換我需要找到該選項,然後替換它的值。不知道是否可以這樣做 – Radek 2010-07-07 04:03:10

+0

啊 - 我假設你知道目前的選項改變是什麼。我正在適當地修改我的答案。 – 2010-07-07 17:39:36

+0

謝謝@Mickey,最後一件事情就是隻在特定的部分進行搜索:-) – Radek 2010-07-08 00:03:35

1

要讀取INI文件,有parse_ini_file。其餘的,你必須爲此寫一個簡單的腳本......或使用sed

+0

我讀的地方,'parse_ini_file'忽略註釋。我需要保存文件。 – Radek 2010-07-07 01:00:47

+0

@Rad然後你沒有機會手動完成它。 – Artefacto 2010-07-07 02:03:16

+0

通過手動我的意思是當然寫腳本:p – Artefacto 2010-07-07 12:12:12