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

邮差的信 提交于 2019-12-24 07:07:16

问题


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?


回答1:


preg_replace('/(\<img[^>]+)(style\=\"[^\"]+\")([^>]+)(>)/', '${1}${3}${4}', $article->text)

this could help




回答2:


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");



回答3:


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.




回答4:


What about something like this?

preg_replace('/<img style="[^"]*"/', '<img ', $article->text);


来源:https://stackoverflow.com/questions/6875518/php-preg-replace-remove-style-from-img-tags

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