試試這個我不能是一個非常真棒選項,但它會奏效。我已經測試過它。爲了接收文件內容,您應該使用$string=file_get_content('config.ini');
而不是我已採取的示例字符串。
Try this code snippet here
<?php
ini_set('display_errors', 1);
/**
* If you do file_get_content('config.ini') that will return you string like this.
* after this you can do it like this. I am taking a sample string.
**/
$string='[SQL_INFO]
defined("DB_MS") ? null : define("DB_MS", "mysqli");
defined("DB_HOST") ? null : define("DB_HOST", "localhost");
[USER_INFO]
defined("USER_NAME") ? null : define("USER_NAME", "ali");
defined("USER_WEB") ? null : define("USER_WEB", "example.com");
[SITE_INFO]
defined("WEBSITE" null : define("WEBSITE", "example.com");
defined("IS_ONLINE") ? null : define("IS_ONLINE", "online");';
preg_match_all('/define\("(\K[A-Za-z\_]+)"\s*,\s*\"([^"]+)/', $string,$matches);
foreach($matches[1] as $key =>$constant)
{
defined($constant) ? null: define($constant, $matches[2][$key]);
}
echo DB_HOST;
解決方案2:注:如果按照這種形態,其中每個部分由線breakes分開會工作。就像你的帖子裏明智一樣。
<?php
ini_set('display_errors', 1);
$string='[SQL_INFO]
defined("DB_MS") ? null : define("DB_MS", "mysqli");
defined("DB_HOST") ? null : define("DB_HOST", "localhost");
[USER_INFO]
defined("USER_NAME") ? null : define("USER_NAME", "ali");
defined("USER_WEB") ? null : define("USER_WEB", "example.com");
[SITE_INFO]
defined("WEBSITE" null : define("WEBSITE", "example.com");
defined("IS_ONLINE") ? null : define("IS_ONLINE", "online");';
$sections= preg_split("/[\n]{2,}/", $string);
$requiredInfo='SITE_INFO';//here you can change the section
foreach($sections as $section)
{
if(preg_match("/\[$requiredInfo\]/", $section,$matches))
{
preg_match_all('/define\("(\K[A-Za-z\_]+)"\s*,\s*\"([^"]+)/', $section,$matches);
foreach($matches[1] as $key =>$constant)
{
defined($constant) ? null: define($constant, $matches[2][$key]);
}
}
}
echo WEBSITE;
我看來像'define'是PHP語言的一部分,而不是非正式的ini文件格式的一部分。請參閱:https://en.wikipedia.org/wiki/INI_file您能否指出我們這樣使用'define'的地方?換句話說:如果你想獲得關於如何解析某些東西的信息,你至少應該確定是什麼東西。 –
我想列出一個表格中的定義值以顯示用於管理它們的內聯編輯define的值。 – MAXX3