tags:

views:

93

answers:

4
+1  Q: 

php regex filename

Hi, anyone can help me with a preg_match? I'd like to use php's preg_match to determine if an input is a valid filename or not (only the filename + file extension, not the full path). General rules:

1) filename = a-z, A-Z, 0-9
2) extension = 3 or 4 letters

Thank you!

+1  A: 

Try this:

preg_match('/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/', $filename)
BoltClock
+1  A: 
/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/

If you want to enforce min/max length for the file name part:

//minimum 4 characters and a maximum of 8 characters

/^[a-zA-Z0-9]{4,8}\.[a-zA-Z]{3,4}$/
Amarghosh
+1  A: 
^\w+\.\w{3,4}$

Should work.

Philipp G
`\w` includes underscores too.
Amarghosh
Oh, yes. You're right.
Philipp G
@Amarghosh: so what? '____.___' is a perfectly valid filename in any OS out there.
stereofrog
@stereofrog Ya, but did you read the question?
Amarghosh
+1  A: 

You can do:

if(preg_match('#^[a-z0-9]+\.[a-z]{3,4}$#i',$filename)) {
        echo "Valid";
}else{
        echo "not Valid";
}
codaddict
`$filename = "foobar.baz\n";`
salathe
@salathe `$` matches before new lines only in multiline mode (with `m` flag).
Amarghosh
@Amarghosh, no it matches before new lines unless told not to (with the `D` modifier)
salathe