PHP若何去掉HTML标签?
正在PHP中能够应用“strip_tags()”函数去掉HTML标签,该函数作用是从字符串中去除了HTML以及PHP标志,其语法是“strip_tags(str) ”,其参数str代表的是要去除了标志的字符串,前往值为解决后的字符串。
演示示例
<?php $text = '<p>Test paragraph.</p><!-- Co妹妹ent --> <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教程》
以上就是PHP若何去掉HTML标签?的具体内容,更多请存眷资源魔其它相干文章!
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!