【发布时间】:2010-03-21 10:39:15
【问题描述】:
如何在缺少结束标签的地方插入结束 html 标签?
喜欢
<tr>
<td>Index No.</td><td>Name</td>
<tr>
<td>1</td><td>Harikrishna</td>
缺少两个结束标记的地方。即“/tr”。现在在这种情况下如何搜索缺少的标记在哪里以及如何插入适当的结束标记,例如“/tr”。
【问题讨论】:
如何在缺少结束标签的地方插入结束 html 标签?
喜欢
<tr>
<td>Index No.</td><td>Name</td>
<tr>
<td>1</td><td>Harikrishna</td>
缺少两个结束标记的地方。即“/tr”。现在在这种情况下如何搜索缺少的标记在哪里以及如何插入适当的结束标记,例如“/tr”。
【问题讨论】:
如果您想处理所有可能的情况,这似乎是一项非常艰巨的任务。 HTML 不是常规语言。恕我直言,您应该尝试从源头上解决问题,这首先是您获得无效 HTML 的方式。
【讨论】:
你可以看看HTML Tidy,看看它是否能满足你的需要。
【讨论】:
我无法对上述内容发表评论,所以我会在此处注明。您也可以使用 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>
【讨论】: