【问题标题】:Inserting Ending Tags For Missing Tags In html在html中插入缺少标签的结束标签
【发布时间】:2010-03-21 10:39:15
【问题描述】:

如何在缺少结束标签的地方插入结束 html 标签?

喜欢

 <tr>
 <td>Index No.</td><td>Name</td>

 <tr>
 <td>1</td><td>Harikrishna</td>

缺少两个结束标记的地方。即“/tr”。现在在这种情况下如何搜索缺少的标记在哪里以及如何插入适当的结束标记,例如“/tr”。

【问题讨论】:

    标签: c# .net html winforms


    【解决方案1】:

    如果您想处理所有可能的情况,这似乎是一项非常艰巨的任务。 HTML 不是常规语言。恕我直言,您应该尝试从源头上解决问题,这首先是您获得无效 HTML 的方式。

    【讨论】:

    • @Darin Dimitro,恕我直言,什么是?
    • @Harikrishna,我的拙见。
    • 我正在使用 Html Agility Pack 来解析 html 内容。如果任何 html 文件缺少标签,则解析不正确。Html Agility Pack 可以帮助在缺少结尾的地方插入结束标签仍然标记?
    【解决方案2】:

    你可以看看HTML Tidy,看看它是否能满足你的需要。

    【讨论】:

    • @Dav,我想编写代码,以便在缺少结束标签的地方插入结束标签。
    • @nobugz,HTML Tidy 是一个工具或源代码,我们可以从中重新生成 html 源代码。如果它是一个工具,那么我们可以编写什么代码来在它们缺少的地方插入结束标记?
    【解决方案3】:

    我无法对上述内容发表评论,所以我会在此处注明。您也可以使用 HTML Tidy 来清理 HTML 片段。在此处查看示例:
    http://www.php.net/manual/en/tidy.examples.basic.php

    HTML Tidy 的替代方法是使用 正则表达式 清理输出代码 - 我在下面提供了一个示例。但是请注意,尽管这在处理方面可能更快,但它并不像 HTML Tidy 那样通用且不健壮(维护方面)。

    代码

    <?php
    
    $html = "
    <table>
    <tr class=\"lorem\">
    <td>Index No.</td>
    <td>Name</td>
    
    <tr>
    <td>0</td>
    <td>FooBaz</td>
    
    <tr>
    <td>1</td>
    <td>Harikrishna</td>
    
    <tr class=\"ipsum\">
    <td>2</td>
    <td>Foo</td>
    </tr>
    
    <tr>
    <td>3</td>
    <td>Bar</td>
    
    
    </table>
    ";
    
    // regex magic
    $start_cond = "<tr(?:\s[^>]*)?>";
    $end_cond = "(?:{$start_cond}|<\/table>)";
    $row_contents = "(?:(?!{$end_cond}).)*";
    
    // first remove all </tr> tags
    $xhtml = preg_replace( "/<\/tr>/ism", "", $html );
    
    // now re-add </tr> tags where appropriate
    $xhtml = preg_replace( "/({$start_cond})({$row_contents})/ism", "$1$2</tr>\n", $xhtml );
    
    // ignore: just for writing comparision output
    echo "<h2>Before:</h2>"; show_count( $html );
    echo "<h2>After</h2>"; show_count( $xhtml );
    
    function cmp($patt,$html) {
        $count = preg_match_all( "/{$patt}/ism", $html, $matches);
        return htmlentities("\n{$count} x {$patt}");
    }
    function show_count($html) {
        echo "<pre>"
            . cmp("<tr(\s[^>]*)?>",$html)
            . cmp("<\/tr>",$html)
            . "</pre>";
    }
    ?>

    输出

    
    Before:
    5 x <tr(\s[^>]*)?>
    1 x <\/tr>
    
    After
    5 x <tr(\s[^>]*)?>
    5 x <\/tr>
    

    【讨论】:

    • 对不起,但恐怕我没有。上面的例子是用 PHP 编写的,但是无论语言如何,正则表达式和执行此操作的逻辑都应该大致相同,前提是该语言支持常用的 PCRE 语法(PCRE = Perl Compatible Regular Expressions)。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2023-01-22
    • 2014-04-22
    • 2020-02-17
    • 2020-11-02
    • 2015-07-04
    • 2017-09-03
    相关资源
    最近更新 更多