找到所有<img>标签,删除高度和宽度,然后将删除的值放在<img>标签的样式中

So I am trying to find a way to get <img> tags from a string remove the width and height of the image and put that info in the style part of the image. Something like this:

I have a string:

<p><img src="image1.jpg" border="0" alt="" hspace="0" vspace="0" width="400px" height="200px" style="display: block; margin-left: auto; margin-right: auto;" /></p>
<p style="text-align: justify;">Some text</p>
<p><img src="iamge2.jpg" border="0" alt="" hspace="0" vspace="0" width="600px" height="300px" style="display: block; margin-left: auto; margin-right: auto;" /></p>

and I would like to get something like this:

 <p><img src="image1.jpg" border="0" alt="" hspace="0" vspace="0" style="width:100%; max-width:400px; display: block; margin-left: auto; margin-right: auto;" /></p>
 <p style="text-align: justify;">Some text</p>
 <p><img src="iamge2.jpg" border="0" alt="" hspace="0" vspace="0" style="width:100%; max-width:400px; display: block; margin-left: auto; margin-right: auto;" /></p>

I tried with preg_replace but it seems I don't understand it well.

Any help is much appreciated. Darko

If the HTML code is valid as XHTML, you can use SimpleXML to find and replace elements and attributes.