文章摘要截取時常因 HTML 標籤未閉合導致頁面樣式錯亂。本文提供一個健壯的 CloseTags() 函數,自動按逆序補全所有未閉合的標籤,並正確處理自閉合標籤。
function CloseTags($html) {
// 移除末尾截斷的標籤片段
$html = preg_replace('/<[^>]*$/', '', $html);
// 提取所有打開標籤
preg_match_all('#<([a-z]+)(?:\s.*)?(?<![/|\s])>#iU', $html, $result);
$opentags = $result[1];
// 提取所有關閉標籤
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closetags = $result[1];
// 已平衡則直接返回
if (count($closetags) == count($opentags)) return $html;
// 逆序補全
$opentags = array_reverse($opentags);
$selfClosing = array('br','input','img','hr','meta','link'); // 自閉合標籤
foreach ($opentags as $tag) {
$lower = strtolower($tag);
if (!in_array($tag, $closetags) && !in_array($lower, $selfClosing)) {
$html .= '</' . $tag . '>';
} else {
unset($closetags[array_search($tag, $closetags)]);
}
}
return $html;
}
$content = '<div><p><span>越發忙碌的你,是否想給自己放個假?...'; echo CloseTags($content); /* 輸出: <div><p><span>越發忙碌的你...</span></p></div> */
#<([a-z]+)(?:\s.*)?(?<![/|\s])>#iU 精準匹配非自閉合的打開標籤。<br>、<img>)。更多 PHP 相關技術請參考專題:《PHP 操作 Office 文檔技巧總結》、《PHP 日期與時間用法總結》、《PHP 面向對象程序設計入門教程》、《PHP 字符串用法總結》、《PHP+MySQL 數據庫操作入門教程》及《PHP 常見數據庫操作技巧匯總》。