PHP实现补齐关闭的HTML标签
网络编程 2021-07-05 09:10www.168986.cn编程入门
这篇文章主要介绍了PHP实现补齐关闭的HTML标签的方法,通过自定义函数实现针对HTML标签的闭合补全功能,涉及PHP字符串及正则匹配相关操作技巧,需要的朋友可以参考下
本文实例讲述了PHP实现补齐关闭的HTML标签。分享给大家供大家参考,具体如下:
很多时候,在我们做文章截取摘要的时候,如果出现HTML的内容,会出现截取的文章没有结束的HTML标签。这样的情况下就会出现页面样式错乱的问题。这 个时候我们需要的就是把缺少的结束标签加批量加上。在.php.官网看到一个比较好处理的一个函数,展示如下:
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相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《》
希望本文所述对大家PHP程序设计有所帮助。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程