本文实例讲述了PHP实现网页内容html标签补全和过滤的方法。分享给大家供大家参考,具体如下:
如果你的网页内容的html标签显示不全,有些表格标签不完整而导致页面混乱,或者把你的内容之外的局部html页面给包含进去了,我们可以写个函数方法来补全html标签以及过滤掉无用的html标签.
代码:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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()解析:
array_reverse() : 此函数将原数组中的元素顺序翻转,创建新的数组并返回。如果第二个参数指定为 true,则元素的键名保持不变,否则键名将丢失。
array_search() : array_search(value,array,strict),此函数与in_array()一样在数组中查找一个键值。如果找到了该值,匹配元素的键名会被返回。如果没找到,则返回 false。 如果第三个参数strict被指定为 true,则只有在数据类型和值都一致时才返回相应元素的键名。
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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():函数删除由addslashes()函数添加的反斜杠。该函数用于清理从数据库或HTML表单中取回的数据。
希望本文所述对大家PHP程序设计有所帮助。
相关文章
猜你喜欢
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 61
-
2025-05-25 47
-
日本网站建设成本:预算有限的情况下如何选择性价比高的服务商?
2025-06-04 101 -
2025-05-29 70
-
2025-05-29 95
热门评论

