使用php删除内联样式

时间:2010-03-21 22:11:19

标签: php inline styles

我使用php输出一些富文本。如何完全去除内联样式?

文本将直接从MS Word或OpenOffice中粘贴到使用TinyMCE的文本中,TinyMCE是一种富文本编辑器,允许您向文本添加基本的HTML格式。 但是我想删除

标签上的内联样式(见下文),但保留

标签本身。

<p style="margin-bottom: 0cm;">A patrol of Zograth apes came round the corner, causing Rosette to pull Rufus into a small alcove, where she pressed her body against his. &ldquo;Sorry.&rdquo; She said, breathing warm air onto the shy man's neck. Rufus trembled.</p>
<p style="margin-bottom: 0cm;">&nbsp;</p>
<p style="margin-bottom: 0cm;">Rosette checked the coast was clear and pulled Rufus out of their hidey hole. They watched as the Zograth walked down a corridor, almost out of sight and then collapsed next to a phallic fountain. As their bodies hit the ground, their guns clattered across the floor. Rosette stopped one with her heel and picked it up immediately, tossing the other one to Rufus. &ldquo;Most of these apes seem to be dying, but you might need this, just to give them a helping hand.&rdquo;</p>

10 个答案:

答案 0 :(得分:27)

我很快将它们放在一起,但对于“内联样式”(!),你需要像

这样的东西
$text = preg_replace('#(<[a-z ]*)(style=("|\')(.*?)("|\'))([a-z ]*>)#', '\\1\\6', $text);

答案 1 :(得分:11)

这是我从Crozin的答案中得到的preg_replace解决方案。这个允许使用锚标记修复问题的样式属性之前和之后的属性。

$value = preg_replace('/(<[^>]*) style=("[^"]+"|\'[^\']+\')([^>]*>)/i', '$1$3', $value);

答案 2 :(得分:5)

使用HtmlPurifier

答案 3 :(得分:2)

您可以使用正则表达式:

$text = preg_relace('#<(.+?)style=(:?"|\')?[^"\']+(:?"|\')?(.*?)>#si', '<a\\1 \\2>', $text);

答案 4 :(得分:0)

难道你不能只使用strip_tags并留下你想要的标签,例如<p>, <strong>等吗?

答案 5 :(得分:0)

为什么不直接覆盖标签。因此,您将拥有没有内联样式的干净标签。

答案 6 :(得分:0)

我发现这个类对于执行条带属性非常有用(特别是在文本中有疯狂的MS Word格式的地方):

http://semlabs.co.uk/journal/php-strip-attributes-class-for-xml-and-html

答案 7 :(得分:0)

您可以使用:$ content = preg_replace(&#39; / style = [^&gt;] * /&#39;,&#39;&#39;,$ content);

答案 8 :(得分:0)

我确实需要从img标签中清除样式,并通过以下代码解决了此问题:

$text = preg_replace('#(<img (.*) style=("|\')(.*?)("|\'))([a-z ]*)#', '<img \\2\\6', $text);
echo  $text;

答案 9 :(得分:0)

您还可以使用PHP Simple HTML DOM Parser,如下所示:

$html = str_get_html(SOME_HTML_STRING);

foreach ($html->find('*[style]') as $item) {
   $item->style = null;
}