php 补齐标签处理,PHP怎么样补齐关闭的HTML标签

PHP空间很多时候,在我们做文章截取摘要的时候,如果出现HTML的内容,会出现截取的文章没有结束的HTML标签。这样的 情况下就会出现页面样式错乱的问题。这 个时候我们需要的就是把缺少的结束标签加批量加上。在www.php.net官网看到一个比较好处理的一个函数, 展示如下:

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('##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 

{

$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;

}

测试使用的结果:

$content = '

越发忙碌的你,是否想给自己放个假?专注工作的你,是否还记得上一次锻炼是什么时候?优伴户外旅行,给你不一样的旅行体验:给心自由,便处处都是风景!';

echo CloseTags($content);

/*

返回的结果是:

越发忙碌的你,是否想给自己放个假?专注工作的你,是否还记得上一次锻炼是什么时候?优伴户外旅行,给你不一样的旅行体验:给心自由,便处处都是风景!

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值