我正在寻找一种方法来删除所有空的HTML标签对,例如
<strong></strong>
和<p class="bold"></p>
。虽然可以相对容易地找到用于此目的的正则表达式,但我找不到一个可靠地与PHP的preg_replace()
配合使用的正则表达式。以下是我尝试过的函数之一(摘自https://stackoverflow.com/a/5573115/1784564):function strip_empty_tags($text) {
// Match empty elements (attribute values may have angle brackets).
$re = '%
# Regex to match an empty HTML 4.01 Transitional element.
< # Opening tag opening "<" delimiter.
((?!iframe)\w+)\b # $1 Tag name.
(?: # Non-capture group for optional attribute(s).
\s+ # Attributes must be separated by whitespace.
[\w\-.:]+ # Attribute name is required for attr=value pair.
(?: # Non-capture group for optional attribute value.
\s*=\s* # Name and value separated by "=" and optional ws.
(?: # Non-capture group for attrib value alternatives.
"[^"]*" # Double quoted string.
| \'[^\']*\' # Single quoted string.
| [\w\-.:]+ # Non-quoted attrib value can be A-Z0-9-._:
) # End of attribute value alternatives.
)? # Attribute value is optional.
)* # Allow zero or more attribute=value pairs
\s* # Whitespace is allowed before closing delimiter.
> # Opening tag closing ">" delimiter.
\s* # Content is zero or more whitespace.
</\1\s*> # Element closing tag.
%x';
while (preg_match($re, $text)) {
// Recursively remove innermost empty elements.
$text = preg_replace($re, '', $text);
}
return $text;
}
这是我一直在测试的HTML:
<strong class="a b">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.l<br class="a b" />fd<br class="a b" /><br class="a b" /></strong><strong class="a b"></strong><strong class="a b"><br class="a b" /></strong><strong class="a b"></strong><br class="a b" /><strong class="a b"><br class="a b" /><br class="a b" /></strong>
到目前为止,我尝试了所有方法(已经花费4个多小时的时间),似乎都能去除一些标签,但并非全部,这让我感到疯狂。如有帮助,将不胜感激。
>\s*</\1>
的正则表达式。(如果你不熟悉正则表达式,可以考虑研究XPath。) - mario<br />
标签)。每个看起来为空的<STRONG>
标签实际上包含两个“``”非空格Unicode字符 - (\uFEFF
)。在我看来,这似乎是一个网页字符编码问题。 - ridgerunner