如何在缺少結束標籤的地方插入結束html標籤?插入缺失標籤的結束標籤在html中
像
<tr>
<td>Index No.</td><td>Name</td>
<tr>
<td>1</td><td>Harikrishna</td>
當兩名失蹤結束tags.That是「在這種情況下/tr".Now如何搜索在哪裏丟失的標籤,有如何插入適當的結束標籤,如」/TR 」。
如何在缺少結束標籤的地方插入結束html標籤?插入缺失標籤的結束標籤在html中
像
<tr>
<td>Index No.</td><td>Name</td>
<tr>
<td>1</td><td>Harikrishna</td>
當兩名失蹤結束tags.That是「在這種情況下/tr".Now如何搜索在哪裏丟失的標籤,有如何插入適當的結束標籤,如」/TR 」。
你可以看看HTML Tidy,看看它是否適合你的需求。
如果你想處理所有可能的情況,這似乎是一個非常重要的任務。 HTML不是一種常規語言。恕我直言,你應該嘗試解決問題的源頭,這是如何在第一個地方你得到無效的HTML。
@Darin Dimitro,什麼是恕我直言? – Harikrishna 2010-03-20 09:19:35
@Harikrishna,在我的拙見。 – 2010-03-20 09:23:21
我使用Html Agility Pack解析html內容。如果有任何html文件存在缺失標記,則解析不會正確完成。可以使用Html Agility Pack幫助將結尾標記插入結尾標記缺失的地方嗎? – Harikrishna 2010-03-20 09:27:18
我無法評論上述內容,所以我會在此處註明。您也可以使用HTML Tidy清理HTML碎片。見的例子在這裏:
http://www.php.net/manual/en/tidy.examples.basic.php
到HTML整潔的另一種方法是用正則表達式來清潔您的輸出碼 - 我下面提供了一個例子。不過請注意,儘管這在處理方面可能會更快,但它並不像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>
@MicE ..你知道c#中的代碼嗎? – Harikrishna 2010-03-23 04:40:12
我很抱歉,但我擔心我沒有。上面的例子是用PHP編寫的,但是正則表達式和用於這樣做的邏輯應該大致相同,無論語言如何,只要該語言支持常用的PCRE語法(PCRE = Perl Compatible Regular Expressions)。 – MicE 2010-03-27 22:23:30
@Dav,我想編寫這樣的代碼,以便在末尾標記缺失的地方插入結束標記。 – Harikrishna 2010-03-20 09:18:49
@ nobugz,HTML Tidy是一個工具或源代碼,我們可以重新生成html源代碼。如果它是一個工具,那麼我們可以寫什麼代碼來將結尾標記插入缺失的地方? – Harikrishna 2010-03-20 10:38:00