使用PHP怎么补齐关闭的HTML标签?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
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>越发忙碌的你,是否想给自己放个假?专注工作的你,是否还记得上一次锻炼是什么时候?优伴户外旅行,给你不一样的旅行体验:给心自由,便处处都是风景!';
echo CloseTags($content);
/*
返回的结果是:
<div><p><span>
越发忙碌的你,是否想给自己放个假?专注工作的你,是否还记得上一次锻炼是什么时候?优伴户外旅行,给你不一样的旅行体验:给心自由,便处处都是风景!</span></p></div>
*/
?>
关于使用PHP怎么补齐关闭的HTML标签问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。