
PHP如何去掉HTML标签?
在PHP中可以使用“strip_tags()”函数去掉HTML标签,该函数作用是从字符串中去除HTML和PHP标记,其语法是“strip_tags(str) ”,其参数str代表的是要去除标记的字符串,返回值为处理后的字符串。
演示示例
<?php
$text = '<p>Test paragraph.</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/1547" title="Favird No-Code Tools"><img
src="https://img.php.cn/upload/ai_manual/000/969/633/68b7a0e82b449361.png" alt="Favird No-Code Tools" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/1547" title="Favird No-Code Tools">Favird No-Code Tools</a>
<p>无代码工具的聚合器</p>
</div>
<a href="/ai/1547" title="Favird No-Code Tools" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><!-- 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><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</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教程》










