6

I'm trying to check whether the last characters of $url are one of the following:

.gif .png .bmp .jpg .jpeg

It works fine for one of them:

if(!preg_match('/\.jpg$/', $url))

but putting them all together isn't working:

if(!preg_match('/[\.gif$\.png$\.bmp$\.jpg$\.jpeg$]/', $url))`

What am I doing wrong?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Alaa M.
  • 4,449
  • 9
  • 48
  • 90
  • The "`!`" part [may or may not be reliable](https://stackoverflow.com/questions/6254239/preg-match-if-not/6254296#6254296) (for instance, false positives or false negatives). That is, even with the correct regular expression, it may still not behave as expected. – Peter Mortensen Feb 23 '22 at 22:53
  • Or in other words, an explicit `!== 0` (compare to ***integer***) for testing for ***regular expression (string) match*** (not `!== false` (Boolean)). Yes, this goes against the advice for other languages, but not following it in this case may result in a lot of hairpulling. – Peter Mortensen Mar 14 '22 at 20:42

2 Answers2

10

You're using a character class when you want alternation...

"/\.(gif|png|bmp|jpe?g)$/"
Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
4

You cannot place "strings" inside a character class. Character classes work with characters, not strings. A character class can match only one out of several characters.

So, the following regex:

/[\.gif$\.png$\.bmp$\.jpg$\.jpeg$]/

matches a single character from the character list between [ and ]. Also, remember that the dot is not a metacharacter inside a character class, so you don't need \. - just . will suffice, but it doesn't matter anyway because this is a wrong approach.

Visual representation:

match

Use alteration to achieve what you want. For example, (foo|bar) matches foo or bar. For your requirements, the following regular expression might work:

/\.(gif|png|bmp|jpe?g)$/

Although, I would not use a regex for this. There's already a function that was built for the exact purpose -- to determine the extension of a file (or URL):

$ext = pathinfo($url, PATHINFO_EXTENSION);
Amal Murali
  • 73,160
  • 18
  • 123
  • 143