[英]PHP preg_replace: remove style=“..” from img tags
I'm trying to find an expression for preg_replace, that deletes all inline css styles for images. 我正在尝试查找preg_replace的表达式,该表达式删除图像的所有内联css样式。 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?
有什么建议么?
preg_replace('/(\<img[^>]+)(style\=\"[^\"]+\")([^>]+)(>)/', '${1}${3}${4}', $article->text)
这可能会有所帮助
As was commented you should use a dom parser, PHP has one built in (two in some cases) called DOMDocument. 如前所述,您应该使用dom解析器,PHP具有一个内置的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");
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. 可以匹配任何东西,
style(.*?)=(.*?)
会继续尝试匹配,直到碰到带有=符号的东西为止,包括各种您不想要的东西。 You also aren't using the g
or m
flags, which I'm pretty sure you want to use. 您也没有使用
g
或m
标志,我敢肯定您要使用它们。
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. 注意
('|")...\\2
,它允许像style="foo 'bar'"
这样的代码。这在style
标签中是很可能的。
那这样的东西呢?
preg_replace('/<img style="[^"]*"/', '<img ', $article->text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.