Log in

View Full Version : Regex Help



ReadyToLearn
03-22-2008, 05:30 PM
Hello everyone,

Say I have a string like this:


$string = "This is a apple. <img src=\"apple.jpg\" /> This is a banana. <img src=\"banana.jpg\" />";

How would I go about extracting only the <img src="\apple.jpg\" />. Basically, how would I extract the first <img> tag that exists within a given string.

Master_script_maker
03-22-2008, 06:49 PM
only the first:

preg_match('/<img src=\\"[a-z0-9]{1,20}[.](jpg|jpeg|gif|png)\\"[ ]?(alt=\\"[a-z0-9]\\")?[ ]?[/]?>/i', $string, $img);
$img[0] will contain the first img tag
Look at updated version below

boogyman
03-24-2008, 12:45 PM
only the first:

preg_match('/<img src=\\"[a-z0-9]{1,20}[.](jpg|jpeg|gif|png)\\"[ ]?(alt=\\"[a-z0-9]\\")?[ ]?[/]?>/i', $string, $img);
$img[0] will contain the first img tag

that doesn't allow for other image tag attributes. like title, width,height being the most probable ones to appear

Master_script_maker
03-24-2008, 03:01 PM
that doesn't allow for other image tag attributes. like title, width,height being the most probable ones to appear
updated version :


preg_match('/<img src=\\"[a-z0-9]{1,20}[.](jpg|jpeg|gif|png)\\"[ ]?(alt=\\"[a-z0-9]\\"[ ]?|title=\\"[a-z0-9]\\"[ ]?|width=\\"[0-9]\\"[ ]?|height=\\"[0-9]\\"[ ]?)*[/]?>/i', $string, $img);