溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PHP去掉HTML標簽的方法

發布時間:2020-06-15 22:53:55 來源:億速云 閱讀:218 作者:元一 欄目:編程語言

概念

HTML的英文全稱是 Hyper Text Marked Language,即超文本標記語言。HTML是由Web的發明者 Tim Berners-Lee和同事 Daniel W. Connolly于1990年創立的一種標記語言,它是標準通用化標記語言SGML的應用。用HTML編寫的超文本文檔稱為HTML文檔,它能獨立于各種操作系統平臺(如UNIX, Windows等)。

PHP即“超文本預處理器”,是一種通用開源腳本語言。PHP是在服務器端執行的腳本語言,與C語言類似,是常用的網站編程語言。根據動態網站要求,PHP語言作為一種語言程序,其專用性逐漸在應用過程中顯現,其技術水平的優劣與否將直接影響網站的運行效率。其特點是具有公開的源代碼, 在程序設計上與通用型語言,如C語言相似性較高,因此在操作過程中簡單易懂,可操作性強。

PHP去掉HTML標簽的方法

在PHP中可以使用“strip_tags()”函數去掉HTML標簽,該函數作用是從字符串中去除HTML和PHP標記,其語法是“strip_tags(str) ”,其參數str代表的是要去除標記的字符串,返回值為處理后的字符串。

演示示例

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";
// 允許 <p> 和 <a>
echo strip_tags($text, '<p><a>');
?>

以上例程會輸出:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

使用示例

<?php
function strip_tags_content($text, $tags = '', $invert = FALSE) {

  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
  $tags = array_unique($tags[1]);
   
  if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE) {
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    }
    else {
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
    }
  }
  elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
  }
  return $text;
}
?>
<?php
function stripUnwantedTagsAndAttrs($html_str){
  $xml = new DOMDocument();
//Suppress warnings: proper error handling is beyond scope of example
  libxml_use_internal_errors(true);
//List the tags you want to allow here, NOTE you MUST allow html and body otherwise entire string will be cleared
  $allowed_tags = array("html", "body", "b", "br", "em", "hr", "i", "li", "ol", "p", "s", "span", "table", "tr", "td", "u", "ul");
//List the attributes you want to allow here
  $allowed_attrs = array ("class", "id", "style");
  if (!strlen($html_str)){return false;}
  if ($xml->loadHTML($html_str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD)){
    foreach ($xml->getElementsByTagName("*") as $tag){
      if (!in_array($tag->tagName, $allowed_tags)){
        $tag->parentNode->removeChild($tag);
      }else{
        foreach ($tag->attributes as $attr){
          if (!in_array($attr->nodeName, $allowed_attrs)){
            $tag->removeAttribute($attr->nodeName);
          }
        }
      }
    }
  }
  return $xml->saveHTML();
}

以上就是PHP如何去掉HTML標簽?的詳細內容,更多請關注億速云其它相關文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女