本文實(shí)例講述了PHP實(shí)現(xiàn)網(wǎng)頁(yè)內(nèi)容html標(biāo)簽補(bǔ)全和過濾的方法。分享給大家供大家參考,具體如下:
如果你的網(wǎng)頁(yè)內(nèi)容的html標(biāo)簽顯示不全,有些表格標(biāo)簽不完整而導(dǎo)致頁(yè)面混亂,或者把你的內(nèi)容之外的局部html頁(yè)面給包含進(jìn)去了,我們可以寫個(gè)函數(shù)方法來(lái)補(bǔ)全html標(biāo)簽以及過濾掉無(wú)用的html標(biāo)簽.
php使HTML標(biāo)簽自動(dòng)補(bǔ)全,閉合,過濾函數(shù)方法一:
代碼:
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()
: 此函數(shù)將原數(shù)組中的元素順序翻轉(zhuǎn),創(chuàng)建新的數(shù)組并返回。如果第二個(gè)參數(shù)指定為 true,則元素的鍵名保持不變,否則鍵名將丟失。
array_search()
: array_search(value,array,strict),此函數(shù)與in_array()一樣在數(shù)組中查找一個(gè)鍵值。如果找到了該值,匹配元素的鍵名會(huì)被返回。如果沒找到,則返回 false。 如果第三個(gè)參數(shù)strict被指定為 true,則只有在數(shù)據(jù)類型和值都一致時(shí)才返回相應(yīng)元素的鍵名。
php使HTML標(biāo)簽自動(dòng)補(bǔ)全,閉合,過濾函數(shù)方法二:
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' ; //允許的標(biāo)簽 $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()
:函數(shù)刪除由addslashes()
函數(shù)添加的反斜杠。該函數(shù)用于清理從數(shù)據(jù)庫(kù)或HTML表單中取回的數(shù)據(jù)。
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。