找到所有标签和更改样式属性

问题描述:

我试图找到一种方式来获得一个字符串标签和删除样式属性。 之后,我想加上我自己的风格,并注意以下文字.. 例如,我有:找到所有<img>标签和更改样式属性

<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p> 

结束endresult应该是:

<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 100%;" /></p><p>&nbsp;</p><p> 

我已经试过unsuccesfully但正则表达式好像我是太愚蠢了解它的功能...

每个帮助将不胜感激!从希腊 吉姆 问候

+0

**不要使用正则表达式来解析HTML **。你不能用正则表达式可靠地解析HTML,你将面临悲伤和挫折。只要HTML从你的期望改变,你的代码就会被破坏。有关如何使用已经编写,测试和调试的PHP模块正确解析HTML的示例,请参阅http://htmlparsing.com/php。 – 2013-04-05 15:46:56

您可以通过正则表达式这样做:

$str = '<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p>'; 

$newStr = preg_replace('#<img (.+) style="(.+)" />#isU', '<img $1 style="width: 100%" />', $str); 
+0

非常感谢你,对于我迟到的回复感到抱歉......这是非常有帮助和容易理解的......继续保持它! – 2013-04-25 09:46:08

要删除高度或一些其他财产:

$string = '<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p' ; 
$pattern = "/height:\s*\d*\s*(px|%);*/" ; 
$new = preg_replace($pattern,"", $string) ; 

echo htmlentities($new) ; 

或移除所有风格的东西,并用自己的替换一些:

$string = '<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p' ; 
$pattern = "/style=[\'\"][^\"|^\']*[\'\"]/" ; 
$own_style = "style='width: 50%'" ; 
$new = preg_replace($pattern, $own_style, $string) ; 

echo htmlentities($new) ; 

一般使用RegExp对HTML标签有点不好,应该避免,但在某些情况下可能适用。

+0

对不起,我迟到的答复......你的答案是非常有益的,我用它在另一个问题..对不起,我不能投两个答案... 据我所知,它不应该被使用,但我不得不更新其containted数据库这些标签,并在6000个条目中这样做看起来像是单向解决方案......完成了这项工作,并学习了更多关于正则表达式的知识!谢谢你的时间! – 2013-04-25 09:48:22