php 去掉指定的html標(biāo)簽及內(nèi)容
來源:程序員人生 發(fā)布時(shí)間:2013-12-19 14:13:06 閱讀次數(shù):4593次
本文章給家收集了大量的關(guān)于html標(biāo)簽的去除方法,很多朋友可能會(huì)想到使用strip_tags函數(shù),但這個(gè)函數(shù)會(huì)把所有的html標(biāo)簽全部刪除了,下面我來給大家介紹去掉指定的html標(biāo)簽及內(nèi)容方法,有需要了解的朋友可參考。
string strip_tags ( string str [, string allowable_tags] )
弊端:這個(gè)函數(shù)只能保留想要的html標(biāo)簽,就是參數(shù)string allowable_tags,在yizero的評論中我知道了這個(gè)函數(shù)的參數(shù)allowable_tags的其他的用法,代碼如下:
strip_tags($source, ”); 去掉所以的html標(biāo)簽。
strip_tags($source, ‘<div><img><em>’); 保留字符串中的div、img、em標(biāo)簽,如果想去掉的html的指定標(biāo)簽,那么這個(gè)函數(shù)就不能滿足需求了,于是乎我用到了這個(gè)函數(shù),代碼如下:
- <?php
-
-
-
-
-
-
-
-
- function replace_html_tag($string, $tagname, $clear = false){
- $re = $clear ? '' : '1';
- $sc = '/<' . $tagname . '(?:s[^>]*)?>([sS]*?)?</' . $tagname . '>/i';
- return preg_replace($sc, $re, $string);
- }
以下是測試代碼,代碼如下:
-
- $string = file_get_contents('http://www.phpfensi.com/');
-
- $string = replace_html_tag($string, 'style', true);
- $string = replace_html_tag($string, 'script', true);
-
- $string = replace_html_tag($string, 'a');
-
- $string = replace_html_tag($string, 'span');
- echo $string;
- ?>
如果我們要?jiǎng)h除指定兩者之間的數(shù)據(jù),代碼如下:
- <?php
-
-
-
-
-
-
- function _strip_tags($tagsArr,$str) {
- foreach ($tagsArr as $tag) {
- $p[]="/(<(?:/".$tag."|".$tag.")[^>]*>)/i";
- }
- $return_str = preg_replace($p,"",$str);
- return $return_str;
- }
-
- $str = "<b>您好</b><input type='text' name='' /><a href='http://www.phpfensi.com'>php粉絲網(wǎng)</a>";
- echo _strip_tags(array("b", "input", "a"),$str); #去掉 B 標(biāo)簽和 INPUT 標(biāo)簽
- ?>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)