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?
You're using a character class when you want alternation...
"/\.(gif|png|bmp|jpe?g)$/"
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:

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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With