對于我的 PHP Web 應用程式,我有一個安裝前/安裝后設定檔案,例如settings-config.php.
從這篇文章中,我們可以使用 PHP 搜索和替換檔案中的確切內容:在檔案中查找和替換
因此,我們可以替換一個精確的字串。說...
'My foo' --becomes--> 'My bar'
...但那是為了匹配精確的字符。
但是,對于某個設定,網路管理員可能在某處輸入了額外的空格,等等。
我的情況
我有一個設定檔案。該設定允許安裝應用程式。完成后,我需要將其設定為false.
| 設定-config.php:
$allowinstall = true; // change to 'true' to allow install
基于那個答案(上面),我創建了這個:
| 搜索替換腳本:
$conf_file = './settings-config.php';
$conf_contents = file_get_contents($conf_file);
$conf_contents = str_replace("allowinstall = true", "allowinstall = false", $conf_contents);
file_put_contents($conf_file, $conf_contents);
但是,從人為因素來看,檔案可能會有所不同
| settings-config.php * : (變體)
$allowinstall = true;
$allowinstall = true;
$allowinstall = true;
$allowinstall = true ;
$allowinstall = true ;
ET_CETERA;
...或者如果不可能發生(它經常在編程中發生),它可能是......
$allowinstall = truth;
$allowinstall = tru;
$allowinstall = truee;
$allowinstall = ture ;
$allowinstall = utre ;
ET_CETERA;
所以,簡單的搜索替換腳本(上圖)對此并不好。
我需要的
我希望以開頭的每一行都$allowinstall = 變成這樣:
$allowinstall = false;
- search-replace 腳本可能應該使用
^一個正則運算式來確保這$allowinstall =是該行內容的開頭,因此注釋不會匹配(即//$allowinstall =不會被更改) - 我想匹配每個實體,所以如果它碰巧設定了不止一次,所有變數都將設定為
$allowinstall = false; - 像這樣的東西:
| 搜索替換腳本:
$conf_file = './settings-config.php';
$conf_contents = file_get_contents($conf_file);
$conf_contents = str_replace(
preg_match("^allowinstall".'/any space/'."=".*),
"allowinstall = false",
$conf_contents
);
file_put_contents($conf_file, $conf_contents);
我不知道如何安全地撰寫該代碼,但我認為如果可以的話最好。無論哪種方式...
對于這種情況,使用 PHP 更新/重置 .php 檔案中的特定設定的“正確”搜索替換腳本是什么?
uj5u.com熱心網友回復:
要使用 執行此操作var_export,您從一個簡單的 PHP 檔案開始,該檔案只包含陣列形式的資料,如下所示:
<?php
$config = [
'foo' => 123,
'bar' => 'abc'
];
您可以將該檔案包含在您需要的位置,然后您可以使用 $config 變數來讀取您需要的值。
然后你操縱你的陣列的內容 fe $config['foo'] = 'xyz';。如果你var_export($config);現在做,這會讓你
array (
'foo' => 'xyz',
'bar' => 'abc',
)
那是“舊”的陣列語法,但它們是可以互換的,所以這并不重要。仍然缺少的是<?php標簽,這個陣列的實際分配給一個變數,以及它后面的尾隨;- 所以這些需要手動添加。
$new = '<?php $config = ' . var_export($config, true) . ';';
var_export 將第二個引數設定為 true,因為我們希望它回傳值,而不是直接輸出。這給你
<?php $config = array (
'foo' => 'xyz',
'bar' => 'abc',
);
- 現在這是完全有效的 PHP 語法,可以按原樣寫入檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477979.html
上一篇:PHPAPI主檔案
