preg_match某些img文件类型

need some help with this bit of pregmatch where I want to look for a specific filetype (jpg, jpeg, png). Any help would be appreciated.

The code:

$strmatch='^\s*(?:<p.*>)?\<a.*href="(.*)">\s*(<img.*src=[\'"].*[\'"]\s*?\/?>)[^\<]*<\/a\>\s*(.*)$';

if (preg_match("/$strmatch/sU", $content, $matches)) { 
        $leadMatch=1;
    }

Right now it does as it is supposed to and returns images, but I want to be able to set image type (ie make it so it doesn't look for .gif)

Thx in advance.

EDIT: Alternatively could it be possible to insert a specific img alt tag to look for, for example alt="thisImage"?

Try this one:

$strmatch='/^\s*(?:<p.*>)?\<a.*href="(.*)">\s*(<img[\sa-z0-9="\']+src="([a-z0-9]+\.[jpeg]{3,4})"[\sa-z0-9="\']*>)[^\<]*<\/a\>\s*(.*)$/ui';
  • NOTE i have put the modifiers on the $strmatch at the end, you should use u-ngreedy and i-nsentive(case)

You may be able to use something like this to grab the images:

<?php

$string = '<a href="index.html" class="bordered-feature-image"><img src="images/3D Logo.jpg" alt="" /></a> <img src="house.png" /> <img src="http://www.google.com/image.gif" alt="" />';

// GRAB THE IMAGES
preg_match_all('~(?<="|\')[A-Z0-9_ /]+\.(?:jpe?g|png)(?=\'|")~i', $string, $images);
$images = $images[0];
print "
Images From Match: "; print_r($images);

You can also, if you'd prefer, store the images in an array and then insert that array into your string. Not that this is necessary for only 2-3 image types, but it's an option if you have a lot of stuff you are wanting to check.

$accepted_image_types = array('jpg', 'jpeg', 'png');

preg_match_all('~(?<="|\')[A-Z0-9_ /]+\.(?:'.implode('|', $accepted_image_types).')(?=\'|")~i', $string, $images);
$images = $images[0];
print "
Images Pulled In From Array: "; print_r($images);

Here is the explanation for the REGEX

~  (?<="|\')  [A-Z0-9_ /]+  \.  (?:jpe?g|png)  (?=\'|")  ~i
        ^           ^       ^        ^            ^
        1           2       3        4            5
  1. (?<="|\') This lookbehind checks to make sure that there is a single or double quote before beginning to match our pattern
  2. [A-Z0-9_ /]+ This is a character class of valid image name characters, followed by a plus to require one or more characters for the file name
  3. \. Matches a literal dot
  4. (?:jpe?g|png) Non-capturing parenthesis that looks for either jpgs or pngs. The question mark after the 'e' makes it optional
  5. (?=\'|") This lookahead checks to make sure that there is a single or double quote after it has matched our pattern

Hopefully that helps!

Here is a working demo