Removing inline styles using php

☆樱花仙子☆ 提交于 2020-01-12 07:17:18

问题


I am using php to output some rich text. How can I strip out the inline styles completely?

The text will be pasted straight out of MS Word, or OpenOffice, and into a which uses TinyMCE, a Rich-Text editor which allows you to add basic HTML formatting to the text. However I want to remove the inline styles on the

tags (see below), but preserve the

tags themselves.

<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>

回答1:


I quickly put this together, but for 'inline styles' (!) you will need something like

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



回答2:


Here is a preg_replace solution I derived from Crozin's answer. This one allows for attributes before and after the style attribute fixing the issue with anchor tags.

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



回答3:


Use HtmlPurifier




回答4:


You could use regular expressions:

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



回答5:


You can also use PHP Simple HTML DOM Parser, as follows:

$html = str_get_html(SOME_HTML_STRING);

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



回答6:


Couldn't you just use strip_tags and leave in the tags you want eg <p>, <strong> etc?




回答7:


Why don't you just overwrite the tags. So you will have clean tags without inline styling.




回答8:


I found this class very useful for doing strip attributes (especially where there's crazy MS Word formatting all through the text):

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




回答9:


You can use: $content = preg_replace('/style=[^>]*/', '', $content);




回答10:


I am did need to clear style from img tags and did resolved by this code:

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


来源:https://stackoverflow.com/questions/2488950/removing-inline-styles-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!