>  기사  >  백엔드 개발  >  PHP에서 HTML 태그를 제거하는 방법은 무엇입니까?

PHP에서 HTML 태그를 제거하는 방법은 무엇입니까?

Guanhui
Guanhui원래의
2020-06-15 15:50:183759검색

PHP에서 HTML 태그를 제거하는 방법은 무엇입니까?

PHP如何去掉HTML标签?

在PHP中可以使用“strip_tags()”函数去掉HTML标签,该函数作用是从字符串中去除HTML和PHP标记,其语法是“strip_tags(str) ”,其参数str代表的是要去除标记的字符串,返回值为处理后的字符串。

演示示例

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

以上例程会输出:

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

使用示例

<?php
function strip_tags_content($text, $tags = &#39;&#39;, $invert = FALSE) {

  preg_match_all(&#39;/<(.+?)[\s]*\/?[\s]*>/si&#39;, trim($tags), $tags);
  $tags = array_unique($tags[1]);
   
  if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE) {
      return preg_replace(&#39;@<(?!(?:&#39;. implode(&#39;|&#39;, $tags) .&#39;)\b)(\w+)\b.*?>.*?</\1>@si&#39;, &#39;&#39;, $text);
    }
    else {
      return preg_replace(&#39;@<(&#39;. implode(&#39;|&#39;, $tags) .&#39;)\b.*?>.*?</\1>@si&#39;, &#39;&#39;, $text);
    }
  }
  elseif($invert == FALSE) {
    return preg_replace(&#39;@<(\w+)\b.*?>.*?</\1>@si&#39;, &#39;&#39;, $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教程

위 내용은 PHP에서 HTML 태그를 제거하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.