您好,欢迎访问一九零五行业门户网

PHP如何去掉HTML标签?

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>
使用示例
<?phpfunction 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;}?>
<?phpfunction 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标签?的详细内容。
其它类似信息

推荐信息