jeffkee
jeffkee

Reputation: 5238

Regular Expression to detect a file extension

I need a regular expression that will detect a filename from a string - see if it ends with .pdf, or .PDF - case insensitive. Should even match .Pdf or any variant of pdf in case the user has messy filenames.

This will be used in PHP 5. I know I can make a bunch of rows to test against each case, but I'm sure there's a more elegant way to do this.

Upvotes: 2

Views: 3269

Answers (5)

ridgerunner
ridgerunner

Reputation: 34395

If your string consists of a single filename here is a simple regex solution:

if (preg_match('/\.pdf$/i', $filename)) {
   // Its a PDF file
}

Upvotes: 0

Pekka
Pekka

Reputation: 449425

There is nothing wrong with a regex, but there is also a ready-made function for dissecting a path and extracting the extension from it:

echo pathinfo("/path/to/myfile.txt", PATHINFO_EXTENSION); //.txt

Upvotes: 9

photoionized
photoionized

Reputation: 5232

As others have noted, extracting the extension would work, otherwise you can do something like this.

preg_match('/.*\.pdf/i', "match_me.pDf", $matches);

Upvotes: 0

The Lazy Coder
The Lazy Coder

Reputation: 11818

another possibility is to tolower the extension

strtolower(pathinfo("/path/file.pDf", PATHINFO_EXTENSION)) == ".pdf"

Upvotes: 0

The Lazy Coder
The Lazy Coder

Reputation: 11818

how about this one. I dont know what language you are using but here is a regex for matching anything ending in .pdf

.+([.][Pp][Dd][Ff]){1}

my bad. Im half asleep. PHP it is. dont know php but that regex should work

Upvotes: 0

Related Questions