在无效的 ini 文件上使用 PHP 函数 parse_ini_file()

Using PHP Function parse_ini_file() on an invalid ini file

我有一个来自外部程序的 ini 文件,我无法控制它。 ini 文件中的值没有双引号 示例:

[Setup]
C SetupCode=Code of the currently installed setup (JOW
C machine configuration). Use a maximum of 8 characters.

使用 parse_ini_file() 给我:syntax error, unexpected ')' 我想我应该阅读 php 中的原始文件并在值周围添加双引号,如下所示:

[Setup]
C SetupCode="Code of the currently installed setup (JOW
C machine configuration). Use a maximum of 8 characters."

这是最佳做法吗?如果是,我该怎么做?

INI 文件格式是一种非正式 标准。存在变体,请参阅 https://en.wikipedia.org/wiki/INI_file
C好像是Comment的意思,但是parse_ini_file()不明白。所以读取ini文件中的字符串,将C替换为;,然后使用parse_ini_string()

<?php
// $ini_string = file_get_contents(...);

// test data
$ini_string = "
[Setup]
C SetupCode=Code of the currently installed setup (JOW
C machine configuration). Use a maximum of 8 characters.
SetupCode=my C ode
";

// replace 'C ' at start of line with '; ' multiline
$ini_string = preg_replace('/^C /m', '; ', $ini_string);

$ini_array = parse_ini_string($ini_string);


print_r($ini_array); // outputs Array ( [SetupCode] => my C ode )