Removing inline styles using php

2020-06-03 03:00发布

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>

10条回答
时光不老,我们不散
2楼-- · 2020-06-03 03:07

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

查看更多
ゆ 、 Hurt°
3楼-- · 2020-06-03 03:10
放我归山
4楼-- · 2020-06-03 03:11

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

查看更多
Fickle 薄情
5楼-- · 2020-06-03 03:17

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;
}
查看更多
We Are One
6楼-- · 2020-06-03 03:17

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;
查看更多
ら.Afraid
7楼-- · 2020-06-03 03:18

You could use regular expressions:

$text = preg_relace('#<(.+?)style=(:?"|\')?[^"\']+(:?"|\')?(.*?)>#si', '<a\\1 \\2>', $text);
查看更多
登录 后发表回答