是否可以使用定义信息解析文件?所以,如果是,有人可以说出我怎么做到这一点?
的config.ini
[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");
PHP:
print_r(parse_ini_file("config.ini"));
答案 0 :(得分:0)
尝试这个我不是一个非常棒的选择,但它会起作用。我测试了它。要接收文件内容,您应该使用$string=file_get_content('config.ini');
而不是我拍摄的示例字符串。
<?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:注意:如果您遵循此模式,其中每个部分由换行符分隔,它将起作用。在你的帖子中也很明智。
<?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;
答案 1 :(得分:0)
PHP具有解析ini文件的功能:parse_ini_file()
或parse_ini_string()