This will match your intended image files with less flexibility (improved accuracy) in the file suffix and more flexibility in the filename.
Pattern: (Demo) /\w+\.(?:gif|png|jpe?g)/i
This will match one or more letters/numbers/underscores, followed by a dot, followed by gif
, png
, jpg
, or jpeg
(case-insensitively).
If you require more file suffixes, you can extend the expression with another alternative by adding a pipe (|
) then your suffix.
If you need to include more possible characters to the front of the filename, you can create a character class like this [\w@!]
which will also allow @
and !
. Or you could change \w
with \S
to match all non-white-characters, but this will slow down your pattern a little.
PHP Code: (Demo)
$str="Match four pictures like this: pic1.jpg, pic2.png, pic3.gif, and pic4.jpeg for example, but not these: document5.pdf and excel7.xls.";
var_export(preg_match_all('/\w+\.(?:gif|png|jpe?g)/i',$str,$out)?$out[0]:'failed');
Output:
array (
0 => 'pic1.jpg',
1 => 'pic2.png',
2 => 'pic3.gif',
3 => 'pic4.jpeg',
)
You will see that by tightening up the file suffix requirements, you can avoid unintentional matches which are not image files.