function CloseTags($html) { // strip fraction of open or close tag from end (e.g. if we take first x characters, we might cut off a tag at the end!) $html = preg_replace('/<[^>]*$/','',$html); // ending with fraction of open tag // put open tags into an array preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result); $opentags = $result[1]; // put all closed tags into an array preg_match_all('#</([a-z]+)>#iU', $html, $result); $closetags = $result[1]; $len_opened = count($opentags); // if all tags are closed, we can return if (count($closetags) == $len_opened) { return $html; } // close tags in reverse order that they were opened $opentags = array_reverse($opentags); // self closing tags $sc = array('br','input','img','hr','meta','link'); // ,'frame','iframe','param','area','base','basefont','col' // should not skip tags that can have content inside! for ($i=0; $i < $len_opened; $i++) { $ot = strtolower($opentags[$i]); if (!in_array($opentags[$i], $closetags) && !in_array($ot,$sc)) { $html .= '</'.$opentags[$i].'>'; } else { unset($closetags[array_search($opentags[$i], $closetags)]); } } return $html; }
測試使用的結果:
<?php
$content = '<div><p><span>越發忙碌的你,是否想給自己放個假?專注工作的你,是否還記得上一次鍛煉是什么時候?優伴戶外旅行,給你不一樣的旅行體驗:給心自由,便處處都是風景!'; www.it165.net
echo CloseTags($content);
/*
返回的結果是:
<div><p><span>
越發忙碌的你,是否想給自己放個假?專注工作的你,是否還記得上一次鍛煉是什么時候?優伴戶外旅行,給你不一樣的旅行體驗:給心自由,便處處都是風景!</span></p></div>
*/
PHP編程鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答