How to remove width and height from <img src="" width="xx" height="yyy" alt="">?

Dear all,

I’m having problem on removing width and height from <img src=“” width=“xx” height=“yyy” alt=“”> .

I tried with the eregi_replace as below:

1st try:

<?php $description= eregi_replace( “height=\”(.*)\“”, “”,$description); ?>

2nd try:
<?php $description= eregi_replace( “height=\”[^]*\“”, “”,$description); ?>

Do you see my error?

where is $description getting it’s data? mind posting it…

Oh, the $description is pulled from database…

Thus the format of the <img src> will be different according to how the user enter the data…

it might be:
Below is my photo<br><img src=“photo.jpg” width=“10” height=“10”><br>


Below is my photo<br><img width=“10” src=“photo.jpg” height=“15”><br>


Below is my photo<br><img width=“20” height=“20” src=“photo.jpg”><br>

4th & 5th try, also not working for these:

<?php $description= eregi_replace( “width=\”([0-9][0-9]?)\“”, “”,$description); ?>

<?php $description= preg_replace( “/[height=\”].+?[\“]/is”, “”,$description); ?>

Try this:

$string = '<img src="" width="xx" height="yyy" alt="">';
$new_string = preg_replace('/\\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\\>/i', '<$1$4$7>', $string);
echo $new_string;

Note this code only works for '<…width=“xx”…height=“yyy”…> format,
if width & height are interchanged(i.e. their occurance) then it doesn’t work.
Can anbody mody the above regular expression to suit the interchangeability?


NVM, didn’t work. :stuck_out_tongue:

It’s working dude.
It prints:

<img src=""   alt="">

Much better. :slight_smile:

$html = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="">
        <img src="path/to/img" height="455" width="455" alt="" />
$doc = DOMDocument::loadHTML($html);
foreach($doc->getElementsByTagName('img') as $image){
    foreach(array('width', 'height') as $attribute_to_remove){
echo $doc->saveHTML();


PHPycho & anthonysterling,

Wow~ Expert solution!

Thanks for you guys sharing!

Outstanding work SilverBullet :slight_smile:

Read my requirements in the quote. Do anybody has idea how to accomplish this using regular expression?

Hi, i found something like this:

preg_match_all(‘/<img[^>]+>/i’,$html, $result);


$img = array();

foreach( $result as $img_tag)
preg_match_all(‘/(alt|title|src)=(“[^”]*")/i’,$img_tag, $img[$img_tag]);


It splits the process in two parts :

* get all the img tag
* extract their metadata

Will this solve the problem???

In your pattern, replace the words “width” and “height” with the following.


Don’t modify anything else, just swap both words out with that.