免责声明:不要使用正则表达式!
不建议使用正则表达式解析 HTML(或任何其他非正则语言)。解决方案失败的陷阱和方法有很多。也就是说,我非常喜欢使用正则表达式来解决复杂的问题,例如涉及嵌套结构的问题。如果其他人提供了有效的非正则表达式解决方案,我建议您使用该解决方案而不是以下解决方案。
正则表达式解决方案:
以下解决方案实现了一个递归正则表达式,它与preg_replace_callback() 函数结合使用(当 FONT 元素的内容包含嵌套的 FONT 元素时,它会递归调用自身)。正则表达式匹配最外层的 FONT 元素(可能包含嵌套的 FONT 元素)。回调函数只去除那些没有属性的 FONT 元素的开始和结束标记。具有属性的 FONT 标签会被保留。我想你会发现这做得很好:
函数 remove_font_tags_without_attr($text)
<?php // test.php Rev:20111219_1100
// Recursive regex matches an outermost FONT element and its contents.
$re = '% # Match outermost FONT element.
< # Start of HTML start tag
( # $1: FONT element start tag.
font # Tag name = FONT
( # $2: FONT start tag attributes.
(?: # Group for zero or more attributes.
\s+ # Required whitespace precedes attrib.
[\w.\-:]+ # Attribute name.
(?: # Group for optional attribute value.
\s*=\s* # Name and value separated by =
(?: # Group for value alternatives.
\'[^\']*\' # Either single quoted,
| "[^"]*" # or double quoted,
| [\w.\-:]+ # or unquoted value.
) # End group of value alternatives.
)? # Attribute value is optional.
)* # Zero or more attributes.
) # End $2: FONT start tag attributes.
\s* # Optional whitespace before closing >.
> # End FONT element start tag.
) # End $1: FONT element start tag.
( # $3: FONT element contents.
(?: # Group for zero or more content alts.
(?R) # Either a nested FONT element.
| # or non-FONT tag stuff.
[^<]* # {normal*} Non-< start of tag stuff.
(?: # Begin "unrolling-the-loop".
< # {special} A "<", but only if it is
(?:!/?font) # NOT start of a <font or </font
[^<]* # more {normal*} Non-< start of tag.
)* # End {(special normal*)*} construct.
)* # Zero or more content alternatives.
) # End $3: FONT element contents.
</font\s*> # FONT element end tag.
%xi';
// Remove matching start and end tags of FONT elements having no attributes.
function remove_font_tags_without_attr($text) {
global $re;
$text = preg_replace_callback($re,
'_remove_font_tags_without_attr_cb', $text);
$text = str_replace("<\0", '<', $text);
return $text;
}
function _remove_font_tags_without_attr_cb($matches) {
global $re;
if (preg_match($re, $matches[3])) {
$matches[3] = preg_replace_callback($re,
'_remove_font_tags_without_attr_cb', $matches[3]);
}
if ($matches[2] == '') { // If this FONT tag has no attributes,
return $matches[3]; // Then strip both start and end tag.
}
// Hide the start and end tags by inserting a temporary null char.
return "<\0". $matches[1] . $matches[3] . "<\0/font>";
}
$data = file_get_contents('testdata.html');
$output = remove_font_tags_without_attr($data);
file_put_contents('testdata_out.html', $output);
?>
示例输入:
<font attrib="value">
<font>
<font attrib="value">
<font>
<font attrib="value">
</font>
</font>
</font>
</font>
</font>
示例输出:
<font attrib="value">
<font attrib="value">
<font attrib="value">
</font>
</font>
</font>
需要正则表达式的复杂性才能正确处理具有可能包含<> 尖括号的值的标签属性。