±¾ÎÄʵÀý½²ÊöÁË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()
½âÎö:
array_reverse()
: ´Ëº¯Êý½«ÔÊý×éÖеÄÔªËØ˳Ðò·×ª£¬´´½¨ÐµÄÊý×é²¢·µ»Ø¡£Èç¹ûµÚ¶þ¸ö²ÎÊýÖ¸¶¨Îª true£¬ÔòÔªËصļüÃû±£³Ö²»±ä£¬·ñÔò¼üÃû½«¶ªÊ§¡£
array_search()
: array_search(value,array,strict),´Ëº¯ÊýÓëin_array()Ò»ÑùÔÚÊý×éÖвéÕÒÒ»¸ö¼üÖµ¡£Èç¹ûÕÒµ½Á˸ÃÖµ£¬Æ¥ÅäÔªËصļüÃû»á±»·µ»Ø¡£Èç¹ûûÕÒµ½£¬Ôò·µ»Ø false¡£ Èç¹ûµÚÈý¸ö²ÎÊýstrict±»Ö¸¶¨Îª true£¬ÔòÖ»ÓÐÔÚÊý¾ÝÀàÐͺÍÖµ¶¼Ò»ÖÂʱ²Å·µ»ØÏàÓ¦ÔªËصļüÃû¡£
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|eva l|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±íµ¥ÖÐÈ¡»ØµÄÊý¾Ý¡£