RegEx replace width and height in an image

i’m horrible at regex and have been banging my head against the wall all morning. i want to replace the image width and height in the img tag in an html snippet. i’ve tried different things and i keep screwing up the img tag.

i want to keep the src and any other attributes the same, set the width to 600 pixels and totally remove the height. anyone have a quick solution?

i tried this to find the width, $rxp=‘/<img.?(width\=[\'|"]{0,1}.?[\’|"]{0,1})[\s|>]{1}/i’;, which works, but i can’t figure out how to replace the original img tag and remove the height.

thanks for any help…

ended up doing this:


$pattern = "/height=\\"[0-9]*\\"/";
$content = preg_replace($pattern, "", $content);
$pattern = "/width=\\"[0-9]*\\"/";
$content = preg_replace($pattern, 'width="600"', $content);

but now that I think about it, that’s really not what I want to do. I should only change the width to 600 if the width is larger than 600.

[sigh]

back to the drawing board…

ok, so now I’m here, but it seems awful verbose:


$rxp='/<img.*?(width\\=[\\'|"]{0,1}.*?[\\'|"]{0,1})[\\s|>]{1}/i';
preg_match($rxp,$content,$match);
$widths=explode('"',$match[1]);

if((int)$widths[1]>600){
   $pattern = "/height=\\"[0-9]*\\"/";
   $content = preg_replace($pattern, "", $content);
   $pattern = "/width=\\"[0-9]*\\"/";
   $content = preg_replace($pattern, 'width="600"', $content);
}

anyone have a cleaner way to do it? Plus I’m not even sure that it’s doing it like I want it. It’s assuming there’s only 1 image tag in the snippet. There could be more images in the snippet.

here’s where I’m at, I think this should do what I’m wanting it to:


$res = preg_match_all('/<img[^>]*>/Ui', $content, $atts);
        $string =  $atts[0][0];
        $pattern = '/(width|height)="[0-9]*"/i';
        preg_match_all($pattern,$string,$dims);

        $dcnt=count($dims);
        for($cnt=0;$cnt<$dcnt;$cnt++){
          $imgw=explode('"',$dims[$cnt][0]);
          $imgh=explode('"',$dims[$cnt][1]);

          if((int)$imgw[1]>600){
            $pattern = '/height="'.$imgh[1].'"/';
            $content = preg_replace($pattern, "", $content);
            $pattern = '/width="'.$imgw[1].'"/';
            $content = preg_replace($pattern, 'width="600"', $content);
          }
        }

what do you think?