我们有时候需要截断html的内容来输出,但是由于截断的位置并不确定,导致阶段后的html内容中的很多标签都没有正常闭合而导致页面变形,如何解决这个问题呢?当然是使用强大的正则表达式来匹配那些没有闭合的标签了,代码如下:
/**
* close all open xhtml tags at the end of the string
*
* @param string $html
* @return string
* @author Milian Wolff <mail@milianw.de
>
*/
function closetags($html) {
#put all opened tags into an array
preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$openedtags = $result[1];
#put all closed tags into an array
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
# all tags are closed
if (count($closedtags) == $len_opened) {
return $html;
}
$openedtags = array_reverse($openedtags);
# close tags
for ($i=0; $i < $len_opened; $i++) {
if (!in_array($openedtags[$i], $closedtags)){
$html .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]);
}
}
return $html;
}
来自:思想之地

