查找所有<img/>标记并更改样式属性

时间:2013-04-05 15:34:41

标签: php regex html-parsing

我正在尝试找到一种从字符串中获取标记并删除样式属性的方法。 之后我想添加自己的风格并保留以下文字.. 例如,我有:

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

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

我没有尝试过正则表达式,但似乎我太愚蠢了解它的功能......

我们将不胜感激! 来自希腊的问候 吉姆

2 个答案:

答案 0 :(得分:3)

你可以通过这样的正则表达式来实现:

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

答案 1 :(得分:1)

删除身高或其他财产:

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

通常在HTML标记上使用RegExp是件坏事,应该避免,但在某些情况下可能适用。