4

i want to check if a file has the extensions .php. if it has i include it.

could someone help me with a regexp check?

thanks!

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
never_had_a_name
  • 90,630
  • 105
  • 267
  • 383

3 Answers3

11

Usually you don't use a regular expression.

The following is a popular method instead:

$extension=pathinfo($filename, PATHINFO_EXTENSION);
zaf
  • 22,776
  • 12
  • 65
  • 95
5

pathinfo is the easiest solution, but you can also use fnmatch

if( fnmatch('*.php', $filename) ) { /* do something */ }

EDIT: Like @zombat points out in the comments, if you are after a fast solution, then the following is faster than using pathinfo and fnmatch:

if( substr($filename, -4) === '.php' ) { /* do something */ }

Keep in mind that pathinfo, unlike fnmatch and substr does a basename check on the path you provide, which makes it somewhat cleaner in my opinion.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 1
    Concerning speed, fnmatch will out perform pathinfo 2:1 when used for this purpose. – webbiedave Apr 22 '10 at 16:30
  • @zaf now that you mention it.. **no, it doesn't**. What made me think that?! LOL. But still, it's slower. – Gordon Apr 22 '10 at 17:15
  • @Gordon you need a slap for that. I'll be scrutinizing all your answers and comments from now on. Watch it. ;) – zaf Apr 22 '10 at 17:18
  • @zaf yes, do so please, otherwise I'll keep spreading lies, unintentionally though, but still :) Best to remove the comment. – Gordon Apr 22 '10 at 17:21
  • @Gordon & @webbiedave check it out http://stackoverflow.com/questions/2693428/pathinfo-vs-fnmatch – zaf Apr 22 '10 at 18:32
  • 2
    If all you're doing is checking for ".php" on the end, why would you ever use something that needed wildcard matching? `if (substr($filename,-4) == '.php')` blows both these methods out of the water in terms of speed. – zombat Apr 22 '10 at 18:53
  • @zombat I gave fnmatch as an alternative to pathinfo because pathinfo was given already and because many people don't seem to know fnmatch exists. Didn't give it because it's faster. I wasn't even aware it is until @webbiedave pointed it out. Yes, substr is faster than both. – Gordon Apr 22 '10 at 20:43
2
/\.php$/

but extension mapping doesn't ensure the content is what you expect, just that a file is named a particular way.

dnagirl
  • 20,196
  • 13
  • 80
  • 123
  • Good point. There are a lot of other file extensions that indicate PHP content: .module, .inc, .test, .install, etc. – David Sep 11 '12 at 17:09