PHP如何去掉HTML標籤?

2020-07-16 10:06:29

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標籤?的詳細內容,更多請關注TW511.COM其它相關文章!