PHP清除指定html標籤二個例子

在php中內置了一個html標籤清除函數strip_tags它刪除的是所有字符串了,如果只要刪除指定的就沒有辦法了。

自定義刪除html標籤函數。

 

例子

 <?php
 function strip_selected_tags($text, $tags = array())
   { www.jbxue.com
       $args = func_get_args();
       $text = array_shift($args);
       $tags = func_num_args() > 2 ? array_diff($args,array($text))  : (array)$tags;
       foreach ($tags as $tag){
           if(preg_match_all('/<'.$tag.'[^>]*>(.*)</'.$tag.'>/iU', $text, $found)){
               $text = str_replace($found[0],$found[1],$text);
         }
       }       return $text;
   }
?>

 

這個函數很短,但它實現的功能很實用,第一個參數是原字符串,第二個參數是要刪除的HTML的標籤數組,如果要刪除<a>和<p>標籤,只需要使用以下代碼:

 

<?php
$tags = array();
$tags[0]='a'; 
$tags[1]='p'; 
 $str = "<a href=http://www.jbxue.com>link</a><p>help</p>";
echo strip_selected_tags($str,$tags);
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章