strip_tags:去掉杂乱的标签和样式 [英] strip_tags: strip off the messy tags and styles
本文介绍了strip_tags:去掉杂乱的标签和样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何剥离某些html标签并允许其中的一些标签? 例如, 我想剥离 span
标记,但允许 span
加下划线。
< span style =text-decoration:underline;>文字< / span>
我想允许 p
但我想例如,删除 p
中的任何样式或类,
< p class =99light> Text< / p>
标签内的类应该被移除 - 我只想要一个干净的 p
标签。 / p>
到目前为止,我已经有这样一行:
strip_tags($内容,< p>< a>< br>< em>< strong>< ul>< li>);
解决方案
你不能。您需要使用XML / HTML解析器来执行此操作:
//使用DOMDocument,它可能看起来像这样。
$ dom = new DOMDocument();
$ dom-> loadHTML($ content);
foreach($ dom-> getElementsByTagName(p)as $ p)
{
//删除p标签中的所有属性。
/ *
foreach($ p-> attributes as $ attrib)
{
$ p-> removeAttributeNode($ attrib);
}
* /
//只删除样式属性。
$ p-> removeAttributeNode($ p-> getAttributeNode(style));
}
echo $ dom-> saveHTML();
How can I strip off certain html tags and allow some of them?
For instance,
I want to strip off span
tags but allow the span
with underline.
<span style="text-decoration: underline;">Text</span>
I want to allow p
but I want to remove any styles or classes inside the p
for instance,
<p class="99light">Text</p>
the class inside the p tag should be removed - I just want a clean p
tag.
The is the line I have so far,
strip_tags($content, '<p><a><br><em><strong><ul><li>');
解决方案
You can't. You'll need to use an XML/HTML parser to do that:
// with DOMDocument it might look something like this.
$dom = new DOMDocument();
$dom->loadHTML( $content );
foreach( $dom->getElementsByTagName( "p" ) as $p )
{
// removes all attributes from a p tag.
/*
foreach( $p->attributes as $attrib )
{
$p->removeAttributeNode( $attrib );
}
*/
// remove only the style attribute.
$p->removeAttributeNode( $p->getAttributeNode( "style" ) );
}
echo $dom->saveHTML();
这篇关于strip_tags:去掉杂乱的标签和样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文