tags:

views:

121

answers:

3

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!

+1  A: 
/\.php$/

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

dnagirl
+9  A: 

Usually you don't use a regular expression.

The following is a popular method instead:

$extension=pathinfo($filename, PATHINFO_EXTENSION);
zaf
+4  A: 

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
Concerning speed, fnmatch will out perform pathinfo 2:1 when used for this purpose.
webbiedave
Based on what evidence?
zaf
@Gordon pathinfo requires file i/o ??? you're pulling my leg...?
zaf
@zaf now that you mention it.. **no, it doesn't**. What made me think that?! LOL. But still, it's slower.
Gordon
@Gordon you need a slap for that. I'll be scrutinizing all your answers and comments from now on. Watch it. ;)
zaf
@zaf yes, do so please, otherwise I'll keep spreading lies, unintentionally though, but still :) Best to remove the comment.
Gordon
zaf
What have I started???
webbiedave
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
@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