PHP preg_replace: remove style=“..” from img tags

2019-07-27 02:04发布

I'm trying to find an expression for preg_replace, that deletes all inline css styles for images. For example, I have this text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. <img style="float:left; margin:0 0 10px 10px;" src="image.jpg" /> Proin vestibulum libero id nisl dignissim eu sodales.

And I need to make it look like:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. <img src="image.jpg" /> Proin vestibulum libero id nisl dignissim eu sodales.

I have tried dozens of expressions like

preg_replace("%<img(.*?)style(.*?)=(.*?)(\'|\")(.+?)(\'|\")(.*?)>%i", "<img\$1\$7>", $article->text)

but nothing worked. Any suggestions?

4条回答
劳资没心,怎么记你
2楼-- · 2019-07-27 02:20

Your pattern is too permissive. Since . could match anything, style(.*?)=(.*?) will go on trying to match until it hits something with a = sign in it, including all sorts of stuff you don't want. You also aren't using the g or m flags, which I'm pretty sure you want to use.

Try something like this:

preg_replace("/<img\s([^>]*)style\s*=\s*('|\").*?\2([^>]*)>/igm", "<img $1 $3>", $article->text)

Note the ('|")...\2, which allows code like style="foo 'bar'". This is quite possible in style tags.

查看更多
相关推荐>>
3楼-- · 2019-07-27 02:25

As was commented you should use a dom parser, PHP has one built in (two in some cases) called DOMDocument. Here is how you could use it for your purpose.

$x = new DOMDocument();
    $x->loadHTMLFile("/path/to/html/file/or/file/outputtinghtml.html");
    foreach($x->getElementsByTagName('img') as $img)
    {
    $img->removeAttribute('style');
    }
$x->saveHTMLFile("/file/used/in/loadHTMLFile/function.html");
查看更多
smile是对你的礼貌
4楼-- · 2019-07-27 02:37

What about something like this?

preg_replace('/<img style="[^"]*"/', '<img ', $article->text);
查看更多
Evening l夕情丶
5楼-- · 2019-07-27 02:40
preg_replace('/(\<img[^>]+)(style\=\"[^\"]+\")([^>]+)(>)/', '${1}${3}${4}', $article->text)

this could help

查看更多
登录 后发表回答