views:

27

answers:

1

The parse_ini_file function removes comments when reading configuration files.

What would you do to keep the comments that are associated with the next line?

For example:

[email]
; Verify that the email's domain has a mail exchange (MX) record.
validate_domain = true

Am thinking of using X(HT)ML and XSLT to transform the content into an INI file (so that the documentation and options can be single sourced). For example:

<h1>email</h1>
<p>Verify that the email's domain has a mail exchange (MX) record.</p>
<dl>
<dt>validate_domain</dt>
<dd>true</dd>
</dl>

Any other ideas?

+1  A: 

You could use preg_match_all to extract comments after [heading] markups:

$txt = file_get_contents("foo.ini");
preg_match_all('/\[([^\]]*)\][[:space:]]*;(.*)/',
    $txt, $matches, PREG_SET_ORDER);

$html = '';

foreach ($matches as $val) {
    $key = trim($val[1]); /* trimming to handle edge case
                             "[ email ]" so $key can be looked up
                              in the parsed .ini */
    $comment = $val[2];

    $html .= "<h1>$key</h1>\n";
    $html .= "<p>$comment</p>\n";
}

echo $html;

foo.ini could contain:

[email]
; Verify that the email's domain has a mail exchange (MX) record.
validate_domain = true ; comment ignored

[s2] ; comment can go here too
foo_bar = true

[s3]
foo_bar = true ; comment also ignored

I didn't play around with parse_ini_file because I don't feel like rebooting to another OS with PHP 5.3, but I think it should be easy to generate the rest of the HTML.

Joey Adams
I think `X(HT)ML -> INI` is a bit more flexible than `INI -> X(HT)ML`. (No edge cases.) However, I'm fairly certain your solution works. Thank you!
Dave Jarvis