Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match for end of string

Tags:

php

preg-match

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?

like image 433
Alaa M. Avatar asked Feb 13 '14 15:02

Alaa M.


2 Answers

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

"/\.(gif|png|bmp|jpe?g)$/"
like image 164
Niet the Dark Absol Avatar answered Sep 29 '22 14:09

Niet the Dark Absol


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);
like image 45
Amal Murali Avatar answered Sep 29 '22 14:09

Amal Murali