【问题标题】:Read line comments in INI file读取 INI 文件中的行注释
【发布时间】:2010-04-17 01:41:14
【问题描述】:

parse_ini_file函数在读取配置文件时会移除cmets。

您将如何保留与下一行关联的 cmets?

例如:

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

我正在考虑使用 X(HT)ML 和 XSLT 将内容转换为 INI 文件(以便文档和选项可以单一来源)。例如:

<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>

还有其他想法吗?

【问题讨论】:

    标签: php documentation single-source


    【解决方案1】:

    您可以使用 preg_match_all 在[heading] 标记之后提取 cmets:

    $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 可能包含:

    [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
    

    我没有使用 parse_ini_file,因为我不想用 PHP 5.3 重新启动到另一个操作系统,但我认为生成 HTML 的其余部分应该很容易。

    【讨论】:

    • 我认为X(HT)ML -&gt; INI 比INI -&gt; X(HT)ML 更灵活一点。 (没有边缘情况。)但是,我相当确定您的解决方案有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2011-05-04
    • 2012-06-29
    • 2011-09-30
    • 2013-04-18
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多