PHP实现网页内容html标签补全和过滤的方法小结【2种方法】
本篇章节讲解PHP实现网页内容html标签补全和过滤的方法。分享给大家供大家参考,具体如下: 如果你的网页内容的html标签显示不全,有些表格标签不完整而导致页面混乱,或者把你的内容之外的局部html页面给包含进去了,我们可以写个函数方法来补全html标签以及过滤掉无用的html标签. php使HTML标签自动补全,闭合,过滤函数方法一: 代码: #iU',$html,$result);
$openedtags = $result[1];
preg_match_all('#([a-z]+)>#iU',$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;
}
php使HTML标签自动补全,过滤函数方法二: /is",$ms);
$searchs[] = '<';
$replaces[] = '<';
$searchs[] = '>';
$replaces[] = '>';
if($ms[1]) {
$allowtags = 'img|font|div|table|tbody|tr|td|th|br|p|b|h3|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"),' .'),$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;
}
更多关于PHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》、《》及《》 希望本文所述对大家PHP程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |