Page 1 of 1

regex image tag

Posted: Mon Sep 26, 2005 12:25 am
by jphamac
I want to post images on my blog but don not want to break the table. I need a code that searches through my string to find image tags, then finds the size of that image. Then it checks if the image is too big and resize it down. I don't need the image to be physically resized but instead just have the html width and height declare it.

Can someone pleaes help. I can do the size conversion to keep the image proportional. i just need the regex that searches for image tags and replace it.

basically, i want to convert:
<img src="http://www.myimage.jpg">

to something like:
<img src-"ttp://www.myimage.jpg" width="500" height="400">


Would it be something like this?

$anchor = preg_replace('/\<img src="([^\]]+)\]([^\[]+)\[\/">\]/i', "<img src=\"$1\">$2 height=\"$h\" width=\"$w\"\">", $string);

Posted: Mon Sep 26, 2005 12:38 am
by feyd
your pattern seems way off.. look over some of the recent threads in this (regex) board for ideas of how to capture the data you need to..

Posted: Tue Sep 27, 2005 4:05 pm
by Skara
I'd physically resize it myself, then turn it into a link that gave a popup of the fullsized image.

Anyway... Let's see... Assuming all images are in the exact format <img src="value">:

Code: Select all

$txt = preg_replace('/(<img src=".+?")>/','$1 width="500" height="400">',$txt);
Now to take into account all variations of the image tag...

Code: Select all

$txt = preg_replace("#(<img[^>]+?)/?>#is","$1 width='500' height='400' />",$txt);
I hope I got that right... >.>

Posted: Tue Sep 27, 2005 8:26 pm
by jphamac
Thanks you so much for helping me out! That's exactly what i wanted.

I originally wanted to get the image size and size it down proportionally but i don't know how to extract just the url of the image so that i can do a imagesize() on it. How do you extract just the image's location?

Your code is perfect but it doesn't work if the tag has border=""

Posted: Wed Sep 28, 2005 11:26 am
by Skara
Your code is perfect but it doesn't work if the tag has border=""
Are you using the first or second one? The first one certainly won't catch it, but the second one should.
How do you extract just the image's location?

Code: Select all

preg_match("#<img.+?src=['\"]([^'\"]+?)['\"][^>]+?>#is",$text,$matches);
//$matches will be an array that holds the info you need.
Should work.. untested.

Posted: Wed Sep 28, 2005 10:27 pm
by jphamac
Scara, thanks you so much. you've been so helpful! :D