这里有新鲜出炉的 PHP 教程,程序狗速度看过来!
PHP(外文名: Hypertext Preprocessor,中文名:"超文本预处理器")是一种通用开源脚本语言。语法吸收了 C 语言、Java 和 Perl 的特点,入门门槛较低,易于学习,使用广泛,主要适用于 web 开发领域。PHP 的文件后缀名为 php。
这篇文章主要介绍了 PHP 实现网页内容 html 标签补全和过滤的方法, 结合实例形式分析了 php 常见的标签检查、补全、闭合、过滤等相关操作技巧, 需要的朋友可以参考下
本文实例讲述了 PHP 实现网页内容 html 标签补全和过滤的方法。分享给大家供大家参考,具体如下:
如果你的网页内容的 html 标签显示不全, 有些表格标签不完整而导致页面混乱, 或者把你的内容之外的局部 html 页面给包含进去了, 我们可以写个函数方法来补全 html 标签以及过滤掉无用的 html 标签.
php 使 HTML 标签自动补全, 闭合, 过滤函数方法一:
代码:
- function closetags($html) {
- preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
- $openedtags = $result[1];
- preg_match_all('#</([a-z]+)>#iU', $html, $result);
- $closedtags = $result[1];
- $len_opened = count($openedtags);
- if (count($closedtags) == $len_opened) {
- return $html;
- }
- $openedtags = array_reverse($openedtags);
- for ($i = 0; $i < $len_opened; $i++) {
- if (!in_array($openedtags[$i], $closedtags)) {
- $html. = '</'.$openedtags[$i].'>';
- } else {
- unset($closedtags[array_search($openedtags[$i], $closedtags)]);
- }
- }
- return $html;
- }
解析:
- closetags()
: 此函数将原数组中的元素顺序翻转,创建新的数组并返回。如果第二个参数指定为 true,则元素的键名保持不变,否则键名将丢失。
- array_reverse()
: array_search(value,array,strict), 此函数与 in_array() 一样在数组中查找一个键值。如果找到了该值,匹配元素的键名会被返回。如果没找到,则返回 false。 如果第三个参数 strict 被指定为 true,则只有在数据类型和值都一致时才返回相应元素的键名。
- array_search()
php 使 HTML 标签自动补全, 闭合, 过滤函数方法二:
- function checkhtml($html) {
- $html = stripslashes($html);
- preg_match_all("/\<([^\<]+)\>/is", $html, $ms);
- $searchs[] = '<';
- $replaces[] = '<';
- $searchs[] = '>';
- $replaces[] = '>';
- if($ms[1]) {
- $allowtags = 'img|font|div|table|tbody|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li';//允许的标签
- $ms[1] = array_unique($ms[1]);
- foreach ($ms[1] as $value) {
- $searchs[] = "<".$value.">";
- $value = shtmlspecialchars($value);
- $value = str_replace(array('\\','/*'), array('.','/.'), $value);
- $value = preg_replace(array("/(javascript|script|eval|behaviour|expression)/i", "/(\s+|"|')on/i"), array('.', ' .'), $value);
- if(!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
- $value = '';
- }
- $replaces[] = empty($value)?'':"<".str_replace('"', '"', $value).">";
- }
- }
- $html = str_replace($searchs, $replaces, $html);
- return $html;
- }
- //取消HTML代码
- function shtmlspecialchars($string) {
- if(is_array($string)) {
- foreach($string as $key => $val) {
- $string[$key] = shtmlspecialchars($val);
- }
- } else {
- $string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
- str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string));
- }
- return $string;
- }
解析:
- checkhtml($html)
: 函数删除由
- stripslashes()
函数添加的反斜杠。该函数用于清理从数据库或 HTML 表单中取回的数据。
- addslashes()
希望本文所述对大家 PHP 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0808/340067.html