php 去掉指定的html標籤及內容

來源:互聯網
上載者:User

string strip_tags ( string str [, string allowable_tags] )

弊端 :

這個函數只能保留想要的html標籤,就是參數string allowable_tags。
在yizero的評論中我知道了這個函數的參數allowable_tags的其他的用法。

 代碼如下 複製代碼

strip_tags($source, ”); 去掉所以的html標籤。

strip_tags($source, ‘<div><img><em>’); 保留字元串中的div、img、em標籤。

如果想去掉的html的指定標籤。那麼這個函數就不能滿足需求了。於是乎我用到了這個函數。

 

 代碼如下 複製代碼
<?php
/**
* 刪除指定的HTML標籤及其中內容,暫時只支援單標籤清理
*
* @param string $string -- 要處理的字串
* @param string $tagname -- 要刪除的標籤名稱
* @param boolean $clear -- 是否刪除標籤內容
* @return string -- 返回處理完的字串
*/
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.111cn.net/');

// 去掉 style 及包含內容
$string = replace_html_tag($string, 'style', true);
$string = replace_html_tag($string, 'script', true);

// 去掉 a 標籤,並儲存其中內容
$string = replace_html_tag($string, 'a');

// 去掉 span 標籤,並儲存其中內容
$string = replace_html_tag($string, 'span');

echo $string;
?>

如果我們要刪除指定兩者之間的資料

 

 代碼如下 複製代碼
<?php
/**  
* PHP去掉特定的html標籤
* @param array $string  
* @param bool $str 
* @return string
*/ 
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.baidu.com'>百度一下,你就知道</a>"; 
echo _strip_tags(array("b", "input", "a"),$str); #去掉 B 標籤和 INPUT 標籤 
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.