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?
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 theg
orm
flags, which I'm pretty sure you want to use.Try something like this:
Note the
('|")...\2
, which allows code likestyle="foo 'bar'"
. This is quite possible instyle
tags.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.
What about something like this?
this could help